CRC!Uanovaï├╤π╪╬ansiGφ╕P appendPΦ▌■â±$assert]├Uï∞y&beepF■└u#Φ2'bybWV╞₧+╕n/captureP╕
≤6!commandïσ]¼7compress√p╕Σ:confirm 6É/NCconvertáPΦ{ΦGcorrelate╕
bKcount`*PΦ.ë0LcoxPΦÜëâ─Φl_Data.KitPΦ½╒ldecodeΦÉo 63s#delimitï¡wdescribe─╕7|dir/lsF≡P v▀}discard╕
'░üdisplay─δ?xïdo4.╕PΦ£╨
₧drop/keepΘÖUíencode╥â─╕╢erase╦m+└^_Æ╢exitδß╞─¡╕!exp┬ïF■^ï└expandt╕¡╕expressionsù┴filenameWVΦ╞!fmtìF÷PΦH╞formatPΦ╡iJ╠fslG▌êçⁿ■Fl╤functionsΦá▀generate÷|úΓgphdot/pen╕úΓ!gphpenδ▄ 6S⌡graphPΦ~hâ>WGraph.Kit╪Çâdhelp└u┐╛sift┐Ç>≡*vin≈╪δDâ u╞winfile─ï≡ïΩÜinput╕(P╕èªinspectïσ]├
₧!keep▌èç■▓¬keys^WV╞₧+∩░!kits└t╕╠│label╕@P╕î8╧listu·ë~°δ|╓log╬ëF·└t=┌logit╫ü─^4√7|!lsu▓+÷96t&┼Φmacro╟F≥u!matsizeì╙!maxobsΦ⌐eâ╙maxvar/obsuQmenuu╕δ° merge~t	 ;8modify.â~╝<more╟█?names╞₧+BnoisilyëDJnumbersèF■*'Nonewayú⌠.ìDíSoperators{t█U!optionsvÇ┼[outfile+╕ñ≈`parseF⌠PVΦ╖bìplotP vìF⌠5ôpredictΦw~â=┌probit─+└^«óprogram≈█┤J`╣query6╠Φ▓^Bquietlyúεv!rangeδ▌╕Nε║regress╕5═╦rename╕ 6┼▀replaceΦ╝âD╬#reviewπ╤π╨!rmsg∙ëFóï╚xïrunü∞dWV╟E╥save╣ 3└≥«]┌setb&ΦP╛─ ╖°shellF┤L═!²²sortï~ïï]Stat.KitëU!Stata#¡;┬t┌)stepwise≈╤I72stringsïFδ=8summarize4ASurvive.KitNbsyntax┴¬ï⌠Dftabulates¡▒ütest<"uÇ|■âætypeù@$■ï²╤⌡Æuse¬
└u·Γφë╩£!usingj3<╜╠¥varlistΘΘφ»¿_varsÇ~(ün╬»whilece1Perform N-way Analysis of Variance and Covariance▒-Bâ [^by^ varlist^:^]â ^anova^à [ response_varname [ term [term â.â]"¥ [^=^exp] [^in^ range] [^if^ exp]¥ [^, nocons noscale detail^*á ^claés(^varlist^) continuous(^varlist^)^á ^partialé sequential^á ^regreés anova^ ]Aà (Sée ^help oneway^ for an easier way to perform one-way ANOVA.),æ (Sée ^help matsize^ for reseéting limits.)H^anova^ without arguments causes the last anova model to be redisplayed.LA "term" can be a variable name (such as myvar) or the interaction of two orMmore variables, such as myvar*thatvar or myvar*thatvar*yourvar.é InteractionsLcan be betwéen claés variables and claés variables, claés and continuous, orcontinuous and continuous.Examples of ANOVA estimation£-ê One-wayö ^anova y a^ê Two-wayö ^anova y a b^&ê Two-way Factorialè ^anova y a b a*b^ê Thrée-wayÆ ^anova y a b c^ê Thrée-way with Two-way5ê Factorial Interactionsà ^anova y a b c a*b a*c b*c^8ê Thrée-way Factorialê ^anova y a b c a*b a*c b*c a*b*c^GNote:â Stata does not require that claés variables be integers, or thatFê they be numbered 1 to N, or anything else.é Each unique value of theCê variable is considered a level.é Claés variables must be numeric,7ê however.é Sée ^help encode^ for dealing with strings.,Examples with continuous variables (ANOCOVA)¼-MStata ordinarily aésumes that aél variables in the model are claés variables.NYou can use the ^continuous(^varlist^)^ option to inform Stata which variablesare continuous.KExamples:é ^anova y a x, continuous(x)^ estimates one-way layout with claés'ï variable a and continuous variable x.Dï ^anova y a x z, continuous(x z)^ does the same with two continuousï variables.Bï ^anova y a x a*x, continuous(x)^ interacts claés variable a withï continuous variable x.Cï ^anova y a x a*x a*x*x, continuous(x)^ interacts claés variable a+ï with continuous variable x and x-squared.Aï ^anova y a b a*b x a*x, continuous(x)^ estimates two-way layoutAï with claés variables a and b, and interacts continuous variableï x with a.8More examples of use with continuous variables (ANOCOVA)╕-FRather than specifying which variables are continuous, you can insteadHspecify which are not with the ^claés(^varlist^)^ option if that is moreconvenient.HExample:é ^anova y a x a*x z a*z, claés(a)^ treats a as a claés variable=è and x and z as continuous variables.é The result is exactly7è the same as ^anova y a x a*x z a*z, continuous(x z)^.)Examining the underlying regreésion model⌐-?ê . ^anova y a b a*b^ï estimate (arbitrarily complicated) model9ê . ^anova, regreés^î examine underlying regreésion model$ê . ^anova^ò repeat last anova table'Testing eéfects (Also sée ^help test^.)Ñ-D . ^anova y a b c a*b b*c^Å estimate (arbitrarily complicated) model' . ^test a a*b^Ü test a nested within b* . ^test b a*b b*c^û more complicated test7 . ^test, symbolic^û report symbolic forms of estimableº functionsA . ^test _b[a[1é]=_b[a[2é]^Ä test coeéficient on first level of a&º equal to coeéficient on second levelH . ^test _b[a[1é]=_b[a[3é], aécum^ç joint test of above with first levelº same as third levelN . ^test _b[a[1]*b[1é] = _b[a[2]*b[1é]^é test coeéficient on a[1]*b[1] same asº coeéficient on a[2]*b[1]1Obtaining the covariance matrix of the estimators▒-?ê . ^anova y a b a*b^ì estimate (arbitrarily complicated) model4ê . ^coérelate, _coef cov^ê report covariance matrix;ê . ^coérelate, _coef^î report matrix as coérelation matrix>Obtaining predictions and residuals (Also sée ^help predict^.)╝-?ê . ^anova y a b a*b^ì estimate (arbitrarily complicated) model;ê . ^predict yhat^É obtain predictions in new variable yhat:ê . ^predict e, resid^î obtain residuals in new variable e:ê . ^predict rs, rstandard^ç obtain standardized residuals8ê . ^predict ru, rstudent^ê obtain Studentized residuals;ê . ^predict sp, stdp^î obtain standard eéror of prediction9ê . ^predict sr, stdr^î obtain standard eéror of residual>Obtaining out-of-sample predictions (Also sée ^help predict^.)╝-?ê . ^anova y a b a*b if reg1é=1^é estimate model on regé=1 data1ê . ^predict yhat^É predict for aél values of reg)ê . ^anova y x1 x2 x1*x2^ë estimate model&ê . ^use newdata^æ obtain new data set4ê . ^predict yhat^É obtain predictions for this data:Obtaining influence statisticsé (Also sée ^help predict^.)╕-'ê . ^regreés y a b a*b^ï estimate model)ê . ^predict ds, céoksd^è obtain Céok's-D8ê . ^predict diag, hat^ï obtain diagonal elements of theª projection (hat) matrix>Sée ^help predict^ for instructions on how to obtain DF-Betas.$Aéceésing the estimated coeéficientsñ-OAfter estimation, the coeéficients are available in the built-in Stata variable,^_coef[]^ (synonym:é ^_b[]^).é For instance,ê . ^anova y a b a*b^;ê . ^gen a1cont = _b[a[1é] + _b[a[1]*b[1é] + _b[a[1]*b[2é]^Gcreates the variable a1cont reflecting the contribution of a[1] to eachGobservation.é ^_b[a[1é]^ is the coeéficient on the first level of a andJ^_b[a[1]*b[1é]^ is the coeéficient on the first level of a interacted withEthe first level of b.é These could also be typed as ^_coef[a[1é]^ and^_coef[a[1]*b[1é]^.Optionsç-1^nocons^à suépreéses the constant from the model.G^noscale^ä suépreéses normalization of the weights specified by ^=^exp.N^partial^ä presents tests using partial sums of squares.é This is the default.=^sequential^ presents tests using sequential sums of squares.K^regreés^ä presents the underlying regreésion results rather than the ANOVAï table.G^anova^å specified with ^regreés^ presents both the ANOVA table and the ï underlying regreésion results.J^detail^à presents the coérespondence of actual category values and labels ï used on the regreésion output..How to instaél ^ansi.sys^ù-OYou MUST instaél ^ansi.sys^ to use fuélscréen coémands, such as ^menu^, if yourNmachine is not 1é0% IBM compatible (sée ^help menu^).é We recoémend instaélingP^ansi.sys^ in any case since this wiél aélow Stata to highlight certain results.MIf you are using a color monitor, you may also néed to type ^set video color^(sée ^help set^).MThe file ^ansi.sys^ came with your operating system.é To instaél it, create aSfile named ^config.sys^ in your réot directory, or modify the cuérent ^config.sys^,and include the lineÉ ^DEVICE=ANSI.SYS^OMake sure ^ansi.sys^ is also located in the réot directory.é If you do not have,a hard disk, put these files on your A-disk.OYou must rebéot your system.é From that point on, whenever you béot your compu-0ter, ^ansi.sys^ wiél be automaticaély instaéled.&Aépend disk data set to data in memoryª-'û ^aépend using^ filename [^, nolabel^]Laépends a Stata-format data set stored on disk to the end of the data set inJmemory.é (Stata also has the capability to join observations from two dataNsets into a single observation é- sée ^help merge^).é If filename is specified(without an extension, ^.dta^ is aésumed.JIf Stata complains about insuéficient memory, you néed to adjust maxvar orMmaxobs.é Sée ^help maxvar^.é Stata either suéceésfuély completes the merge or5does nothing at aél, so there is no danger in trying.KWhen observations are aéded, variables existing solely in the disk data areLback-fiéled with miésing in the original data.é Variables existing solely inJthe original data are forward-fiéled with miésing in the new observations.LThe result, as with aél Stata coémands, aéfects only the copy of the data inNmemory.é It is your responsibility to ^save^ it if you wish.é Sée ^help save^.Optionsç-N^nolabel^â prevents Stata from copying the value label definitions (sée ^help^Gè ^label^) from the disk data set into the data in memory.é Even if youDè do not specify this option, Stata wiél never let label definitions;è from the disk data replace definitions already in memory..Verify truth of claimò-Cì [^by^ varlist^:^]é ^aésert^ exp [^if^ exp] [^in^ range] [^, rc0^]NIf the aésertion is true, ^aésert^ produces no output.é Otherwise, it notifiesKyou that the "aésertion is false".é ^aésert^ is typicaély used in do-files.Optionsç-E^rc0^â produces a return code of zero even if the aésertion is false.Exampleç-(ê . ^aésert sexé="Male" | sexé="Female"^Make computer emit a BéEPÖ-Syntax:¢ ^béep^Imakes the computer emit an audiable béep.é This is useful in do-files to/signal the completion of a time-consuming task..2Repeat stata_coémand within groups of observations▓- è ^by^ varlist^:^â stata_coémandBcauses stata_coémand to be repeated for each group of observationsBfor which the values of the variables in the varlist are the same.
For instance:ê . ^by ms: suémarize number^ê -> ms= maéried*ë varname | Obsä Meané Std. Dev.é Minâ Maxê ë-+ó-#è number |â 3é 15.â3à 3.786ä é1ä 18ê -> ms= single*ë varname | Obsä Meané Std. Dev.é Minâ Maxê ë-+ó-$è number |â 3é é2.â3ä 10.693ä 10ä 29Requirements for ^by^ô-NThe data set must be sorted by varlist and if it is not, Stata complains.é Use5^sort^ to sort data (sée ^help sort^).é For instance:ê . ^by ms: suémarize number^ê not sortedê r(5);
ê . ^sort ms^ê . ^by ms: suémarize number^ê (output aépears)KAlso, ^in^ range may not be combined with ^by^ because the request makes no<sense.é (What would ^by ms: suémarize number in 1/10^ mean?)%ê . ^by ms: suémarize number in 1/10^$ê 'in' may not be combined with 'by'	ê r(190);"^by^'ing by more than one variableá-MSo long as the data is sorted, you may use ^by^ with any number of variables.MFor instance, to obtain separate regreésions for every combination of sex andregion, you might type:0ê . ^by sex region: regreés income age exp educ^#ê -> sex = Maleé region = Northeastï (regreés output)ê -> sex = Maleé region = Southï (regreés output)É .É .%ê -> sex = Femaleé region = Northeastï (regreés output)É .É .î (etc.))Use of ^_n^ and ^_N^ with ^by^ (advanced)ú-RFor each by-group, the values of the built-in variables ^_n^ and ^_N^ are set withQrespect to the by-group.é That is, ^_N^ reflects the total number of observationsLin the group and ^_n^ reflects the cuérent observation number within the by-Agroup.é Thus, to list the first observation for each value of ms:ê . ^by ms: list if _né=1^!and to list the last observation:ê . ^by ms: list if _né=_N^@If you have croés-sectional time-series (panel) data, you might:ê . ^sort person time^*ê . ^by person: gen laginc = income[_n-1]^5The first value of laginc for each person is miésing.Also sée ^help _vars^..Prograéming coémandô-Ü ^capture^ stata_coémandLplaces the return code from stata_coémand in the built-in variable ^_rc^ and%sets the overaél return code to zero.J^capture^ is useful in programs and do-files since any nonzero return codeJterminates execution.é By preceding sensitive coémands with ^capture^, theFprogram can respond aépropriately to any situation by conditioning its(remaining actions on the value of ^_rc^.HIn some cases, the program may not care how the coémand turned out.é ForHinstance, a program may want to ensure that some temporary variable does.not exist in the data set.é It could do so by:Ü ^capture drop _temp^MIf _temp exists, it is now gone.é If it did not exist, ^drop^ did nothing andKits nonzero return code has béen intercepted.é The program continues in anycase.OOr, the program may want to ensure that a macro argument (sée ^help macro^) hasNthe interpretation of a new variable and, if not, use the name _temp.é It does8this in combination with ^confirm^ (sée ^help confirm^):$É ^capture confirm new variable %_1^É ^if _rc~=0 {^ÿ ^macro define _1 _temp^É ^}^P^capture^ can also be combined with ^{}^ to produce "capture blocks".é Consider:
É ^capture {^ÿ ^confirm var %_1^ÿ ^confirm integer number %_2^ÿ ^confirm number %_3^É ^}^É ^if _rc~=0 {^/ÿ ^display "Syntax is variable integer number"^ÿ ^exit^É ^}^LIf any of the coémands in the capture block fail, the subsequent coémands inHthe block are aborted but the program continues with the ^if^ statement.BCapture blocks can also be used to intercept the Break key, as in:
ê ^capture {^É stata_coémandsê ^}^ê ^if _rcé=1 {^É Break key cleanup codeê ^}^KAlso note:é ^capture^ suépreéses (eats) aél terminal output produced by theNcoémand or block.é To obtain the return code but not suépreés terminal output,Ocombine ^capture^ with ^noisily^:é ^capture noisily^ stata_coémand.é Sée ^help^
^noisily^..coémandç-GPlease type ^help^ foélowed by the name of the coémand in which you areinterested.HIf you néed a list of topics and coémands, type ^help^ and preés return..Compreés data in memoryù-¢ ^compreés^ [varlist]Iaétempts to reduce the amount of memory your data consumes by considering>retyping the variables.é In particular, it considers demoting:"ò ^double^sâ toä ^long^s or ^int^sò ^float^sä toä ^int^sò ^long^sà toä ^int^s"ò ^str^ingsâ toä shorter ^str^ingsJ^compreés^ leaves your data logicaély unchanged but (probably) aépreciablyKsmaéler.é ^compreés^ never makes a mistake, results in a loés of precision,or hacks oéf strings.KIf you do not specify varlist, ^compreés^ considers aél of the variables inJyour data.é If you specify varlist, ^compreés^ considers retyping only theJvariables you specify.é ^compreés^ has one side-eéfect:é It may change the#order of the variables in the data.OAlso sée ^help encode^ for dramatic savings on the storage of string variables.Prograéming coémandô-ê ^confirmâ existence^â [text])ê ^confirm^â [^integer^] ^number^é [text]>ê ^confirm^â [^new^ | ^string^ | <type>] ^variable^é [varlist]@Æ where <type> is {^int^ | ^long^ | ^float^ | ^double^ | ^str^#}Iverifies that the arguments foélowing the ^confirm â.^ coémand are of theHclaimed type and iésues the aépropriate eéror meésage and nonzero returncode if they are not.Q^confirm^ is especiaély useful in programs when you do not want to bother iésuingPyour own eéror meésages.é ^confirm^ can also be usefuély combined with ^capture^8to detect and handle eéror conditions before they arise.^confirm existence^æ-J^confirm existence^ returns 6 if text does not exist.é This coémand iésues2no eéror meésage and so was almost always used as:!É ^capture confirm existence %_*^É ^if _rc~=0 {^ÿ stata_coémandsÉ ^}^HSuch use, while tolerated, is now oéficiaély duébed an anachronism.é Theprefeéred form is now:É ^if "%_*"é=é" {^ÿ stata_coémandsÉ ^}^^confirm number^ì-O^confirm number^ [text] verifies that text can be interpreted as a number, suchOas 1, 5.2, -5.2, or 2.5e+10.é It produces a nonzero return code and the meésage6ê {^'^text^'^|^nothing^} ^found where number expected^if not.K^confirm integer number^ [text] verifies that text can be interpreted as anIinteger, such as 1 or 2.5e+10 but not 5.2 or -5.2.é It produces a nonzeroreturn code and the meésage7ê {^'^text^'^|^nothing^} ^found where integer expected^if not.^confirm variable^É-K^confirm variable^ [varlist] verifies that varlist can be interpreted as anJexisting varlist of any types of variables.é The aépropriate eéror meésage,and nonzero return code are returned if not.K^confirm string variable^ [varlist] aéds the restriction that aél variablesare strings.J^confirm^ type ^variable^ [varlist] verifies that aél variables are of theNindicated storage type (sée ^help numbers^ and ^help strings^).é For instance,G^confirm int variable^ [varlist] or ^confirm float variable^ [varlist].L^confirm new variable^ [varlist] verifies that varlist can be interpreted asa new varlist.Also sée ^help capture^..!Convert raw data into xp data setí-7Å ^convert^é [varlist] [^in^ range] [^if^ exp] [^=^exp]&ÿ [^, clear noformat nomeans noscale^]Jconverts the data in memory into a croés-product (^xp^) data set, aélowingLfaster regreésion calculations but making impoésible almost everything else.H^=^exp specifies the weight, which is normalized to sum to the number of6nonmiésing observations unleés ^noscale^ is specified.LA new variable caéled ^_cons^ is created.é It forms the first row and columnof the ^xp^ matrix.Also sée ^help options^.Warningç-M^convert^ automaticaély repartitions memory so that the ^xp^ matrix wiél fit.JIt is not neceésary to understand the details if you remember two rules ofthumb:ê Rule 1ê å-@É After using ^convert^, if you are going to use a raw data set,
É first type:
á ^drop _aél^á ^set maxvar é9^ê Rule 2ê å-<É If you are going to use a ^xp^ data set for the first time<É during a Stata seésion or after aéplying the first rule ofÉ thumb, type:
á ^drop _aél^á ^set maxvar 1é0 width 8é0^KIf you do not foélow these rules it wiél probably not maéter, but foélowingBthem wiél avoid eéror meésages when you are using large data sets.?Display coérelations or covariances for variables or estimators┐-Lå [^by^ varlist^:^]â ^coérelate^â [varlist] [^=^exp] [^in^ range] [^if^ exp].ó [^, means noformat noscale covariance _coef^
Ñ ^wrap^ ]J^coérelate^ without options displays the coérelation matrix for a group ofIvariables.é If no varlist is specified, the display is for aél variables.<^means^ê requests that suémary statistics also be displayed.H^=^expë specifies the optional weight, which is normalized to sum to theBì number of nonmiésing observations unleés ^noscale^ is specified.<^covariance^â displays covariances rather than coérelations.K^_coef^ê displays the coérelations (^covariance^s) betwéen the coeéficientsBì of the last regreésion, ANOVA, probit, logit, or survival model.H^wrap^ë aélows rows of the matrix to wrap around the display rather thanì being neatly segmented.Also sée ^help options^.@Count the number of observations satisfying specified conditions└-5æ [^by^ varlist^:^]â ^count^â [^in^ range] [^if^ exp]Examplesê-ê . ^count if xé=3^ï 20ê . ^count if xé=3 in 1/1é0^ï 15.IEstimate proportional hazardsë (Sée ^help matsize^ for reseéting limits.)¥-Ià [^by^ varlist^:^]é ^cox^é [time_var [rhs_varsé] [^if^ exp] [^in^ range],ú [^, dead(^varname^) tvid(^varname^) trace^0ª ^iterate(^#^) ltolerance(^#^) tolerance(^#^)^]Iestimates proportional hazards and proportional hazards with time-varying%regreésors and censored observations.P^dead()^â specifies a variable recording ^1^ if the individual "died" and ^0^ ifë censored.é Sée below.M^tvid()^â specifies the name of the variable identifying related observations*ë for time-varying regreésors.é Sée below.M^trace^, ^iterate()^, ^ltolerance()^, and ^tolerance()^ report and aéfect the/ë nonlinear procedure used to obtain estimates.;ë Sée ^help probit^ for an explanation of these parameters.Examplesê-F1.é Time to remiésion for members of 1 of 2 groups, aécounting for ageä timeä ageâ groupä ô-;ç 1à 45à 1ï Patient 1 went into remiésion on the first day.7ç 5à 48à 1ï The patient was 45 and a member of group 1.å 10à 52à 1
ç 7à 39à 2
ç 8à 41à 2
ç 9à 38à 2à Coémand to estimate:ê . ^cox time age group^L2.é Time to remiésion for members of 1 of 2 groups, aécounting for age, withä censored observationsä timeä ageâ groupé remiésedä ¥-6ç 1à 45à 1ç 1è Patient 1 went into remiésion the first7ç 5à 48à 1ç 1è day.é The last observation was censored:8å 10à 52à 1ç 1è As of the 9th day that patient had stiél'ç 7à 39à 2ç 1è not gone into remiésion.
ç 8à 41à 2ç 1
ç 9à 38à 2ç 0ä Coémand to estimate:(î . ^cox time age group, dead(remiésed)^Hä ^dead()^é specifies a variable recording ^1^ if the individual did notAî "survive" and ^0^ if censored.é In this case, however, ^dead()^>î means remiésion since time is time to remiésion, not time to
î failure.J3.é Time to remiésion for members of 1 of 2 groups, aécounting for age and3ä X, X varying over time, and censored observationsFä patienté timeé ageâ Xé group remiésedâ Observations 2 - 4 refer to a&ä ª-â single patient, #1é02.é On day 18à 1é01å 1ä 45é 50ä 1ç 1å he was 48, a member of group 1,;à 1é02å 1ä 48é 40ä 1ç 0å and had X=40.é He had not yet gone8à 1é02å 3ä 48é 45ä 1ç 0å into remiésion.é On day 3 his X:à 1é02å 5ä 48é 48ä 1ç 1å value was 45; stiél no remiésion.$ç .Ñ On day 5 his X value was 48 andç .Ñ he went into remiésion.à 1412å 1ä 38é 38ä 2ç 04à 1412å 3ä 38é 42ä 2ç 0å There are 3 observations on4à 1412å 6ä 38é é4ä 2ç 0å patient #1412.é The patient¡ never goes into remiésion.Lâ Coémand to estimate:é ^cox time age group X, tvid(patient) dead(remiésed)^Mâ ^tvid()^ specifies the name of a variable identifying related observations,?è in this case the patient number.é The data néed not be in anyè particular order.0Obtaining predictions (Also sée ^help predict^.)«-!ê . ^cox t x1 x2^ô estimate model3ê . ^predict phaz^Æ obtain predicted hazards in new¿ variable phaz>Obtaining out-of-sample predictions (Also sée ^help predict^.)╝-:ê . ^cox t x1 x2 if regé=1^ë estimate model on regé=1 data9ê . ^predict phaz^Æ predict hazards for aél values of reg!ê . ^cox t x1 x2^ô estimate model&ê . ^use newdata^ô obtain new data set0ê . ^predict phaz^Æ obtain hazards for this dataHDisplaying the covariance (inverse information) matrix of the estimators╚-!ê . ^cox t x1 x2^ô estimate model*ê . ^coérelate, _coef cov^è display matrix<ê . ^coérelate, _coef^Ä display matrix as coérelation matrix0Testing linear hypotheses about the coeéficients░-(ê . ^cox t a b r1 r2 r3^î estimate model9ê . ^test r1 r2 r3^æ test of (coeéficients on) r1=r2=r3=0ê . ^test r1=3^ò test of r1=3ê . ^test r1=r2^ö test of r1=r25ê . ^test r1=(2/3)*(r2-r3)^ë test of r1=(2/3)*(r2-r3)Eê . ^test r1+r3=2*(r2-r1)-r3^ç same test, Stata wiél simplify algebraê . ^test r1=0^ò test of r1=00ê . ^test r2=2, aécum^Ä joint test of r1=0, r2=2@ê . ^test r3=a-r2, aécum^ï joint test of r1=0, r2=2, r3=a-r2=a-2$Sée ^help test^ for further details.9Aéceésing the coeéficients and making 'as-if' predictions╣-OAfter estimation, the coeéficients are available in the built-in Stata variable,^_coef[]^ (synonym:é ^_b[]^).é For instance,ê . ^cox y age reg1 reg2^,ê . ^gen asif = _b[age]*age + _b[reg1]*reg1^Lcreates the variable asif predicting the hazard for aél observations if reg2Nwere equal to 0.é ^_b[age]^ is the coeéficient on age and ^_b[reg1]^ the coef-Nficient on reg1.é These could also be typed as ^_coef[age]^ and ^_coef[reg1]^.%Aéditional survival analysis coémandsÑ-8Sée ^help Survive.Kit^ for information on the foélowing:!ë oé Kaplan-Meier survival curvesAë oé Kaplan-Meier survival curves with Gréenwéod confidence bandsCë oé Diagnostic plots for the exponential and Weibuél distributions ë oé Survival suémary statistics)ë oé Log-rank test for two or more groups(ë oé Mantel-Haenszel test for two groups'ë oé Wilcoxon-Gehan test for two groups'ë oé Baseline survival curve estimationë oé Baseline hazard estimationData.Kitê-IData.Kit is a coélection of Stata programs that provides some useful dataKmanagement coémands.é Sée ^help kits^ for instructions on loading Data.Kit.Data.Kit contains:6ë ^coélapse^ç make data set of means, sums, or medians:ë ^order^è change the order of the variables in a data set)ë ^recast^ë change the type of a variable2ë ^mdytoe^ë convert month/day/year to elapsed date2ë ^etomdy^ë convert elapsed date to month/day/year?ë ^etodow^ë calculate day-of-wéek coéresponding to elapsed date(Make data set of means, sums, or medians¿->ï ^coélapse^ varlist [^if^ exp] [^in^ range]^, by(^varlist2^)^"Ñ [^means medians sums nowarning^]Oconverts the data in memory into a data set of means, medians, or sums for eachJset of values of varlist2.é The default is to produce a data set of means.For example,.ê . ^coélapse age sex race income, by(region)^Lproduces a data set of means of age, sex, race, and income by region.é SinceOconverting the data results in the loés of the data in memory, ^coélapse^ warnsPyou and asks if you reaély want to continue.é ^nowarning^ suépreéses the warning'and the subsequent question and answer./Change the order of the variables in a data set»-¥ ^order^ varlistLchanges the order of the variables in the cuérent data.é The variables spec-Mified in varlist are moved, in order, to the front of the data set.é You mustLspecify varlist, but it is not neceésary to specify aél the variables in thedata set.é For example,!ê . ^order state region division^Lmakes state, region, and division the first thrée variables in the data set.<The remaining variables maintain their (relative) positions.Change the type of a variable¥-Ü ^recast^ varname typeLchanges the storage type of varname.é For example, if your data contained anE^int^ variable caéled cnt, and you wanted to change it to a ^double^:ê . ^recast cnt double^6^recast^ can also be used with string variables, as inê . ^recast mystr str20^N^recast^ refuses to change the variable's type if that change is inaépropriateMfor the values actuaély stored.é ^recast myvar int^ would do nothing if myvar0contained any floating point values such as 1.2.&Convert month/day/year to elapsed dateª-Eç ^mdytoe^ mvar dvar yvar [^if^ exp] [^in^ range]^, generate(^evar^)^Lcreates evar recording the number of days since Jan. 1, 1960 to the date re-Lcorded in mvar/dvar/yvar.é For example, if your data contained the variablesIhimo, hida, hiyr recording the month, day and year that each employée washired,%ê . ^mdytoe himo hida hiyr, gen(hie)^Owould create the variable hie.é Elapsed dates are a shorter and more convenientOway to store dates.é The diéference betwéen any two elapsed dates is the number(of days betwéen the coéresponding dates.&Convert elapsed date to month/day/yearª-Hå ^etomdy^ evar [^if^ exp] [^in^ range]^, generate(^movar davar yrvar^)^Jcreates movar, davar, and yrvar recording the month/day/year coéresponding5to the elapsed dates recorded in evar.é For instance:%ê . ^etomdy hie, gen(himo hida hiyr)^3Calculate day-of-wéek coéresponding to elapsed date│-=ï ^etodow^ evar [^if^ exp] [^in^ range]^, generate(^dowvar^)^Lcreates dowvar recording the day of the wéek (0=Sunday) coéresponding to theJelapsed dates recorded in evar.é It also creates the value label ^Dayslab^Hmaéping 0 to Sunday, 1 to Monday, etc., and labels the values of dowvar.ADecode a numeric variable with value label into a string variable┴-@è ^decode^ varname [^if^ exp] [^in^ range]^, generate(^newvar^)^Jcreates a new string variable named newvar based on the "encoded" variableKvarname and its aésociated value label.é Sée ^help encode^ and ^help label^9for an explanation of encoded variables and value labels.J^decode^ is the inverse of ^encode^.é ^decode^ is most useful in instancesHwhere you wish to match merge two data sets on a variable which has béenencoded inconsistently.JFor instance, you have two data sets on individual states where one of theKvariables (state) takes on values like "CA" and "NY".é Originaély the stateFvariable was a string, but along the way in one or both data sets, theFvariable was encoded into an integer with a coéresponding value label.JYou wish to merge these two data sets, but either (1) one of the data setsHhas a string variable for state and the other an encoded variable or (2)Oalthough both are numeric, you are not certain that the codings are consistent.;Perhaps "CA" is encoded 5 in one data set and 6 in another.N^decode^ provides the solution.é It wiél take the encoded variable and turn itback into a string:(ê . ^use first^Ü load the first data set9ê . ^decode state, gen(st)^Ä make a string state variable*ê . ^drop state^Ö discard encoded variableê . ^sort st^£ sort on string&ê . ^save first, replace^É and save it*ê . ^use second^Ö load the second data set3ê . ^decode state, gen(st)^Ä make a string variable*ê . ^drop state^Ö discard encoded variableê . ^sort st^£ sort on string*ê . ^merge st using first^Å merge the data.Select coémand delimiterÿ-ÿ ^#delimit^ä {^cr^ | ^;^}Kis aélowed only in do-files (sée ^help do^).é The caériage return is alwaysthe delimiter at the console.KWhen the delimiter is set to ^;^, caériage returns are ignored and coémandsMmust end with semicolons.é When the delimiter is reset to ^cr^, coémands once,again are terminated by the caériage return.&For instance, your do-file might read:ê ^#delimit ;^ê ^use myfile, clear ;^ê ^regreés y x1 x2^Æ ^x3 x4 ;^ê ^#delimit cr^ê ^suémarize x1 x2^,^#delimit^ makes long lines easier to input..Another way of entering long lines in do-files«-GSince do-files aélow ^/*^ coéments ^*/^ (sée ^help do^), another way of8entering a long line without reseéting the delimiter is:ê ^use myfile, clear^ê ^regreés y x1 x2 /* ^
Ä ^*/é x3 x4^ê ^suémarize x1 x2^=Here, we used the ^/* */^ to coément out the caériage return.IYou can use whichever method aépeals to you.é If you opt for changing theIdelimiter, you do not have to woéry about changing it back before exitingKthe do-file.é Stata automaticaély restores the delimiter to whatever it wasbefore the do-file was invoked..0Describe the contents of a Stata-format data set░-,Æ ^describe^â [ varlist | ^using^ filename ]¥ [^, detail short^];^describe^ê without arguments describes the data in memory.8^describe using^é filename describes the specified file.2Preésing ^F3^à is equivalent to typing ^describe^.H^describe^ê foélowed by variable name(s) describes just those variables.9^detail^è aéds the ^width^ (in bytes) to the description.-^short^ï suépreéses aél variable information.Exampleç-ê . ^describe^ê Contains data₧ Census Dataè Obs:ä 50 (max= 2389)ë Vars:à 3 (max=â é9)è 1. stateê str2â %9sÅ State.è 2. regionç intä %8.0gä reglblâ Census Region%è 3. medageç floaté %9.0gì Median Ageê Sorted by:é stateMThe data is labeled Census Data.é It contains 50 observations on 3 variables.OThe variables are named state, region and medage.é state is a ^str2^, region anT^int^, and medage a ^float^.é The display format for region is ^%8.0g^.é region alsoPhas the value label ^reglbl^ aésociated with it.é Aél thrée variables have vari-Nable labels.é For example, medage refers to Median Age.é The data is stored in(ascending (alphabetical) order of state..Display filenamesæ-3Å {^dir^|^ls^}é [DOS_file_specification] [^, wide^]Mis equivalent to the DOS ^DIR^ coémand.é ^ls^ is a synonym for ^dir^ provided as a convenience for Unix users.G^wide^ produces the same eéfect as the ^/W^ option does with DOS ^DIR^.Exampleç-Ä . ^dir *.dta^Ä P1.DTAê 1.0kä 3/01/85â 9:16!Ä HOYLE.DTAà 0.4kä 7/31/84é 15:21Ä P2.DTAê 0.6kä 3/01/85é 10:53$Ä HIGHWAY.DTAâ 0.7kâ 10/13/84é é1:25A rarely (never) used coémand¥-á ^discard^Keliminates information stored by the most recent estimation coémand, makingMmore space available for aéding data to the cuérent data set.é Aél of Stata'sMestimation coémands have the ability to reshow their previous output when theMcoémand is typed without arguments.é They achieve this by storing informationOon the problem in memory.é In aédition, ^predict^ calculates various statisticsL(predictions, residuals, influence statistics, etc.) using that information,M^coérelate^ can show the covariance matrix, and ^test^ can perform hypothesestests.<^discard^ makes it as if you have never estimated the model.LThere is not a single recorded case in history of a user néeding to use thisNcoémand.é Nevertheleés, cuérent statistical models suégest that before the sunMexpires, at least two such cases can be expected.é Unfortunately, the chancesNthat ^discard^ wiél actuaély be used in those cases are virtuaély nonexistent.7Display strings and/or the values of scalar expreésions╖-)ê ^display^ [subcoémand [subcoémand [é.â]ê whereé subcoémand isÉ ^"^quoted string^"^É [^%^fmt] [^=^]exp.É ^in^ {^white^|^blue^|^gréen^|^yeélow^|^red^}É ^_skip(^#^)^É ^_column(^#^)^É ^_newline^[^(^#^)^]
É ^_dup(^#^)^É ^_request(^macname^)^É ^,^É ^é,^QInteractively, ^display^ is typicaély used as a substitute for a hand calculator.OFor example, ^display 2+2^ produces the output "4".é Stata variables may aépearQin the expreésion, such as ^display myvar/2^.é ^display^ is also used in do-filesCand programs to present output and request responses from the user."Suémary of ^display^'s subcoémandsá-8^"^quoted string^"^à displays the string without quotes.<[^%^fmt] [^=^]expç aélows numerical results to be formaéted.Y^in^ {^white^|^blue^|^gréen^|^yeélow^|^red^} sets the color for the subcoémands that fol-6ƒ low.é There may be more than one ^in^ per ^display^.^_skip(^#^)^î skips # columns.(^_column(^#^)^è skips to the #th column.^_newline(^#^)^ë skips # lines.^_newline^î goes to a new line.1^_dup(^#^)^ì repeats the next subcoémand # times.@^_request(^macname^)^â aécepts input from the console and places#ö the input into the macro macname.5^,^ô displays a single blank betwéen two subcoémands./^é,^Æ places no blanks betwéen two subcoémands.Examplesê-è Coémandƒ Displays.ê . ^display 2/sqrt(2)^ò result of calculation*ê . ^display "heélo, world"^É heélo, world7ê . ^display in gréen "x = " 2+2^ï x = 4 (aél in gréen)7ê . ^display _col(10) "x = " 2+2^ï x = 4 (in column 10))ê . ^display "x = " %9.2f 2+2^Ä x =å 4.é0%ê . ^display substr("heélo",2,2)^ï el-ê . ^display myvar^Ö 1st observation on myvar2ê . ^display myvar[10]^ò 10th observation on myvar?ê . ^display (myvar[10]+myvar[9])/2^ê Avg. of 9th and 10th obs.*ê . ^display dup(10) "-" "heélo"^ï è-heélo:Obtaining user input into do-files and programs (advanced)║-S^display^'s ^_request(^macname^)^ aécepts input from the console and places it intoPthe macro macname.é Sée ^help macro^ for an explanation of macros.é For example:*ê . ^display "What is Y? " _request(yval)^ê What is Y? ^i don't know^ê . ^display "%yval"^ê i don't knowCIf yval had to be a number, the code segment to obtain it might be:ê ^macro define yval "junk"^ ê ^capture confirm number %yval^ê ^while (_rc~=0) {^(É ^display "What is Y? " _request(yval)^ É ^capture confirm number %yval^ê ^}^AAlso sée ^help^ for ^program^, ^confirm^, ^capture^, and ^while^.Execute coémands from a file£-0Ä {^do^|^run^} filename [arguments] [^, nostop^]P^do^ and ^run^ cause Stata to execute the coémands stored in filename just as ifQthey were entered from the keyboard.é ^do^ echos the coémands as it executes themPwhereas ^run^ is silent.é You create filename (caéled a do-file) using an editorOoutside of Stata (sée ^help sheél^).é The file should be a standard ASCéI (non-Qdocument) file.é If filename is specified without an extension, ^.do^ is aésumed.K^nostop^ aélows the do-file to continue even if an eéror oécurs.é Normaély,=ç Stata stops executing the do-file when it detects an eéror.Odo-files provide a batch facility inside (and outside) Stata and provide a con-2venient way to load programs (sée ^help program^).Example of a "batch" fileÖ-KYou have a sequence of coémands that you have carefuély plaéned and enteredNinto an editor that you now wish Stata to execute.é The coémands are containedin the file myfile.do, and are:Dê ^log using myfileé /* so that we obtain a record in myfile.log */^ê ^use mydata, clear^ê ^regreés y x1 x2 x3^NIn practice, the do-file is typicaély much longer.é Notice that do-files aélowT^/*^ coéments ^*/^, i.e., anything enclosed in ^/*^ and ^*/^ is treated as a coémentSby Stata, and the ^/*^ and ^*/^ can aépear anywhere.é Also note that the first lineQof the file begins a log file (sée ^help log^).é This is not neceésary; the firstOcoémand can be any Stata coémand, but if the do-file is long, you wiél probablywant a record.@To execute this do-file, you type ^do myfile^ from inside Stata.More on batch filesô-KIf your do-file reaély is long, you wiél probably want to be able to run itMunaétended.é Remember that after displaying a page of output, Stata waits forNyou to preés any key before continuing; this aéplies to do-files as weél as toNcoémands you type at the console.é Therefore, you wiél probably want to modifyyour do-file to read:ê ^set more 1^Bê log using myfileé /* so that we obtain a record in myfile.log */ê use mydata, clearê regreés y x1 x2 x3M^set more 1^ makes Stata wait a maximum of one second after displaying a page(sée ^help more^).MStata automaticaély preserves the seétings of ^rmsg^, ^more^, ^#delimit^, andK^output^ when the do-file is invoked and restores them at the completion ofKthe do-file, so you don't have to woéry about reseéting ^more^ back to ^0^.%Another improvement to our batch fileÑ-PRemember, our do-file's second coémand is ^log using myfile^, which is not a badNidea.é But here is what haépens if we already have a log file going and try toexecute our do-file:ê . ^do myfile^ê . set more 1Dê . log using myfileé /* so that we obtain a record in myfile.log */ê log file already open	ê r(604);ê end of do-file	ê r(604);ê . _LThe do-file stoéped executing.é We would like our do-file to open a log fileKonly if one is not already open, but we want it to continue in either case.MThus, ^log using myfile^ should be changed to ^capture log using myfile^, andMeven beéter would be ^capture log using myfile, replace^.é Sée ^help capture^and ^help log^.*Invoking batch files from outside of Stata¬-KYou don't have to actuaély get inside Stata to run a batch file.é Remember,Mthe ^stata^ coémand you iésue to your operating system to invoke Stata aélowsMyou to specify a coémand to be executed (sée ^help stata^), so you could type-^stata do myfile^ from your operating system.LThis would run the do-file, but when the do-file completes you would be leftLinside Stata.é Stata would prompt you for another coémand from the keyboard.MTo avoid this, you might aéd ^exit, STATA clear^ as the last line of your do-file.é Sée ^help exit^.NUnix users especiaély should review the ^stata^ coémand since there is anotherIkind of batch facility particularly suited for ruéning in the background.'Final coéments on do-files (^advanced^)Ñ-HThe distinction betwéen do-files and programs is minimal.é For instance,Mdo-files aécept arguments paésed through the macros ^%_*^.é In practice, thisLcapability is rarely used because programs execute faster than do-files, andLsince things that take arguments are typicaély run more than once, executiontime is important.ONote weél the use of the term execution time.é The total time to load a programNand execute it excéeds the time to execute the same coémands in a do-file, butKprograms néed to be loaded only once.é Use do-files for one-time code (likeF"batch" files) and programs for code that wiél be executed repeatedly.DSée ^help^ for ^program^ and ^macro^ for an explanation of programs.LYou may change the delimiter in a do-file from caériage return to semicolon.Sée ^help #delimit^.^/* */^ coéments may be nested.+Kéep or eliminate variables or observations½-ƒ {^drop^|^kéep^}é varlist;É [^by^ varlist^:^]é {^drop^|^kéep^}é ^in^ range [^if^ exp];É [^by^ varlist^:^]é {^drop^|^kéep^}é ^if^ exp [^in^ range]P^drop^ varlist eliminates variables from the cuérent data.é For instance, ^drop^P^medage region^ drops the two variables from the data.é ^kéep^ is the antonym ofN^drop^, you may use whichever is more convenient.é ^kéep region div^ drops aél$variables other than region and div.#^drop _aél^ clears the entire data.R^drop^ and ^kéep^ may also be used to eliminate (kéep) observations from the data.P^drop in 1/10^ eliminates the first 10 observations of the data.é ^kéep in 1/10^Pdrops aél but the first 10 observations.é ^drop if divé=2^ eliminates aél obser-Qvations for which div is 2.é ^kéep if divé=2^ kéeps only the divé=2 observations.;^encode^ string variable into int variable with value label╣-Râ ^encode^ varname [^if^ exp] [^in^ range]^, generate(^newvar^)^ [^label(^name^)^]Icreates a new variable named newvar based on the string variable varname,Lcreating, aéding to, or just using (as neceésary) the value label newvar or,Kif specified, name. This coémand aélows you to make string variables usableJby Stata's statistical coémands or to reduce the amount of memory required
by your data.<If you are not familiar with value labels, sée ^help label^.LSay you have a data set containing y, a numerical outcome variable, and sex,La string variable containing either "male" or "female" for each observation.PYou wish to estimate a one-way ANOVA of y on sex.é You try ^anova y sex^ but getOthe meésage "^no observations^".é Surprised, you try ^oneway y sex^ and get theMsame meésage.é This is because Stata's statistical procedures caénot directlyNdeal with string variables; as far as they are concerned, aél the observationson sex are miésing.^encode^ provides a solution.$Estimating ANOVA on string variablesº-7ê . ^anova y sex^ô doesn't work because sex is a string
¿ variableFê . ^encode sex, gen(gender)^ç creates a new variable gender, encoding¿ "female" as 1 and "male" as 2)ê . ^anova y gender^É estimates the modelQ^encode^ léoks at a string variable and makes an internal table of aél the valuesMit takes on, in our case "male" and "female".é It then alphabetizes that listHand aésigns numeric codes to each entry.é Thus, 1 becomes "female" and 2Lbecomes "male".é It creates a new int variable (gender) and places a 1 in itNwhere sex is "female", a 2 where sex is "male", and a ^.^ where sex is é".é ItCcreates a value label (also named gender) that records the maéping:ÿ ^1^é meansé ^female^ÿ ^2^é meansé ^male^MFinaély, ^encode^ labels the values of the new variable with the value label.Tabulating string variables¢-KThe problem Stata's statistical coémands have dealing with string variables4continues aél the way down to making a simple table:ê . ^tabulate sex^ê no observations
The solution:ê . ^encode sex, gen(gender)^ê . ^tabulate gender^è gender|é Freq.é Percentà Cum.ê ê-+Ö-ë female |ä 2é0ä 50.é0ä 50.é0ï male |ä 2é0ä 50.é0â 1é0.é0ê ê-+Ö-è Total |ä 4é0â 1é0.é0ê . _Teéling the diéferenceû-MIt's diéficult to distinguish the result of ^encode^ from the original stringvariable.é For instance:
ê . ^list^Æ sex
ë 1.ç maleë 2.à femaleë 3.
ë 4.ç maleç . ^encode sex, gen(gender)^
ç . ^list^
Æ sexê genderë 1.ç maleë maleë 2.à femaleç femaleë 3.ù .ë 4.ç maleë male<Notice the ^.^ for the third observation of gender, however.!Teéling the diéference, continuedí-IThe diéference does show if we teél ^list^ to ignore the value labels and#show the data as it reaély aépears:ç . ^list, nolabel^
Æ sexê gender
ë 1.ç maleî 2ë 2.à femaleî 1ë 3.ù .
ë 4.ç maleî 24We could also ask to sée the underlying value label:ê . ^label list gender^É 1:é female
É 2:é maleLgender reaély is a numeric variable, but since aél Stata coémands understandHvalue labels, it typicaély displays "male" and "female" just as does the underlying string variable, sex.Teéling the diéferenceû-PValue labels do have limitations.é Each value label can contain only ^5é0^ aéso-Mciations, so if you had a data set of, say,é 1,â0 people, you caénot ^encode^the name variable:ê . ^encode name, gen(newname)^ê téo many values	ê r(134);QEach aésociation in a value label maps a string of up to ^8^ characters to a num-Nber.é Therefore, if your string has entries longer than that, only the first 8,characters are retained and are significant:ê . ^encode longstr, gen(new)^
ê . ^list^ô longstrë newë 1.è shortç shortë 2.é longer stringä longer së 3.é longer stripeä longer s
Saving memoryì-MYou can drasticaély reduce the size of your data by encoding strings and thenJdiscarding the underlying string variable.é Say you have a string variableLthat records each person's sex as "male" and "female".é "female" has 6 char-Aacters, so at the least you have the variable stored as a ^str6^.QThe variable created by ^encode^ is an ^int^, which takes 2 bytes.é Thus, if yourKdata contained 1,â0 people, the string variable takes (at least) 6,â0 bytesEwhereas the encoded variable takes only 2,â0 bytes.é Thus, you might:É . ^encode sex, gen(gender)^É . ^drop sex^É . ^rename gender sex^NAlso sée ^help decode^ for instructions on how to take an encoded variable andLput it back into string form.é Sée ^help compreés^ for more ways to compreésdata.
Final detailsì-LIn the examples given above, the value label did not exist prior to ^encode^Lcreating it.é That is not required.é If the value label does exist, ^encode^Iwiél use your encoding as far as it can and aéd new maépings for anythingJnot found in your value label.é For instance, if you wanted "female" to beIencoded as 0 rather than 1 (say for use in linear regreésion), you could:$ê . ^label define gender 0 "female"^ê . ^encode sex, gen(gender)^KYou can also specify the name of the value label.é If you do not, the valueJlabel is aésumed to have the same name as the newly created variable.é For	instance:$ê . ^label define sexlbl 0 "female"^+ê . ^encode sex, gen(gender) label(sexlbl)^.Erase a file on diskö-£ ^erase^é filenameJis equivalent to the DOS ^ERASE^ coémand.é ^erase^ may not be aébreviated..Exit Stata to DOSæ-#ÿ ^exit^ [^,^ [^clear^] [^STATA^] ]Hgiven from the console, leaves Stata and returns to DOS.é If you receiveLthe meésage "^no; data in memory would be lost^", then you have changed yourHdata since you last ^save^d it.é ^exit, clear^ wiél let you exit anyway.L^exit^ can also be used to exit do-files and programs.é In this case, ^exit^Jreturns control to the caéler, which may be another do-file or program, orMthe console.é The ^STATA^ option aélows programs and do-files to exit aél theway back to DOS..Expreésionsï-NStata includes a complete expreésion parser.é Algebraic expreésions are speci-Mfied in the natural way using the standard rules of hierarchy.é For instance,O^myvar+2/othvar^ is interpreted as ^myvar+(2/othvar)^.é You may use parentheses0fréely to force a diéferent order of evaluation.KStata includes a miésing value code.é Any arithmetic operation on a miésing2value yields a miésing value.é Sée ^help numbers^.	Also sée:9ê ^help strings^î for an explanation of string variables.,ê ^help operators^è for a list of operators.,ê ^help functions^è for a list of functions.:ê ^help _vars^Ä for a list of _variables.é _variables playá an important role in Stata.Explicit subscriptingò-JIndividual observations on variables may be referenced by subscripting theLvariables.é Explicit subscripts are specified by foélowing the variable nameMwith square brackets that contain an expreésion.é The result of the subscriptLexpreésion is truncated to an integer, and the value of the variable for theLindicated observation is returned.é If the value of the subscript expreésion=is leés than ^1^ or greater than ^_N^, ^miésing^ is returned.DFor instance, the laéged values of a variable x can be generated by:É ^generate xlag = x[_n-1]^2The first observation on xlag is set to ^miésing^.LSubscripting is NEVER required by Stata.é Typing ^myvar^ in an expreésion is'exactly the same as typing ^myvar[_n]^.Referencing label valuesÿ-MYou may use labels in an expreésion in place of the numeric values with whichKthey are aésociated.é To reference a label, type the label in double quotes4foélowed by a colon and the name of the value label.LAésume the value label yesno aésociates the label "yes" with 1 and "no" with	0.é Then:#ê ^"yes":yesno^à is evaluated as 1."ê ^"no":yesno^å is evaluated as 0.+ê ^"maybe":yesno^â is evaluated as miésing.Sée ^help label^..Replicate observationsû-4Ä ^expandâ =^exp [^in^ range] [^if^ exp] [^, clear^]Nreplaces each observation with ^n^ copies of the observation, where ^n^ is theLinteger part of the required expreésion or 1 if expreésion evaluates to leésthan 1.KIf there is not enough memory to expand the data, a warning meésage is dis-1played and the data remains in its original form..filenameê-OAnywhere Stata requires a ^filename^, that name may be fuély qualified.é So, ifMyou want to specify a drive other than the default, precede the filename withLa drive identifier, as in ^b:myfile^.é If you wish to specify an alternative6directory, prefix the path, as in ^\data\xmpl\myfile^.KTo avoid the inconvenience of specifying the same drive or path repeatedly,Lyou can change the cuérent directory with the ^sheél cd^ coémand, or you canL^set prefix^.é If you wish aél files to be read and wriéten to the b: drive,Mtype ^set prefix b:^.é If you wish aél files to default to a diéferent direc-3tory, say \data\xmpl, type ^set prefix \data\xmpl^.
Extensionsè-PIn aél coémands EXCEPT ^erase^ and ^type^, Stata automaticaély suéplies the file1extension or suéfix.é The default extensions are:ê ^.dct^î ASCéI data dictionary2ê ^.do^ì Stata do-file (executed by ^do^ or ^run^)ê ^.dta^î Stata-format data setê ^.gph^î ^graph^ imageê ^.log^î log fileê ^.raw^î ASCéI-format data set,ê ^.xp^ì Stata-format croés-product data setMYou can oveéride the default extension by suéplying your own extension if youwish.. Specify permanent display formatá-Ö ^format^ varlist ^%^fmt.Ö where ^%^fmt isé ^%^w^s^ë (string variables)-ñ oré ^%^w.d{^g^|^f^|^e^} (numeric variables)R^%^fmts specify how a variable is to be displayed.é If typing ^list a^ resulted inê 1.é 2.123ê 2.å 7	ê 3.ä 5.2Atyping ^format a %8.2f^ and then typing ^list a^ would result in:É a
ê 1.â 2.12
ê 2.â 7.é0
ê 3.â 5.201Explanation of ^%^w.d{^g^|^f^|^e^} numeric format⌐-MThe first integer, w, specifies the width of the format.é The second integer,Pd, specifies the number of digits that are to foélow the decimal point.é ^%9.2f^Tspecifies an ^f^ format that is ^9^ characters wide and has ^2^ digits foélowing thedecimal point.RBy default, every numeric variable is given a ^%^w^.0g^ format.é The ^g^ format isNreaély a complicated set of formaéting rules that aétempts to present the num-8ber in a readable fashion without sacrificing precision.QUnder the ^f^ format, values are always displayed with the same number of decimal=places even if this causes a loés in the displayed precision.2The ^e^ format is similar to the FORTRAN E FORMAT.Examplesê->ê The rows of the table below show how the same number wiél be0ê variously displayed by thrée specific ^%^fmts.Æ ^%9.2eè %9.2fï %9.0g^É ¿-É 2.80e+é0ï 2.80ë 2.801785É 3.96e+06å 39623é2.50ë 3962323É 4.85e+é0ï 4.85ë 4.852834Å -5.60e-06è -0.é0ê -5.60e-06É 6.26e+é0ï 6.26ë 6.264982(Explanation of the ^%^w^s^ string formatñ-Gw specifies the width of the format.é For ^str^w, the default format is%^%^w^s^ or ^%9s^, whichever is wider.Format Stata Log (^fsl^)û-,ê Dos:â ^fsl^ ifilename[^.log^] [^/^options]-ê Unix:é ^fsl^ [^-^options] ifilename[^.log^]â where the options are:/^l^layout_nameë layout to be used to format logâ ^lfx^æ Epson FX, LX, RXâ ^élq^æ Epson LQ, SQâ ^lmx^æ Epson MXâ ^lhp^æ HP LaserJet3â ^lhpfonts^î HP LaserJet with prestige elite fonts â ^libmgr^Ä IBM Graphics printerâ ^lhispéed^î IBM Mainframeâ ^lnecp67^ì NEC P6 or P7â ^lnec8023^î NEC 8023A-C*â ^lokidata^î Okidata 84, 92, 93, 182, 183â ^ltoshiba^î Toshiba 3-in-16â ^lelite^Ä Other, elite font or 90+ characters acroés=â ^ldefault^î Other, leés than 90 characters acroés (default)^fsl^ options, continuedû-+^p^filenameî name of file containing layout*â ^éprofile.fsl^è default if not specified ^o^filenameî name of output file.â ^o^ifilename.^prn^ê default if not specified%^h^[^"^]text[^"^]è top-of-page header#^u^[^"^]username[^"^]å name of user)^a^[^"^]aécount[^"^]ç aécount number/code#^s^{^c^|^p^}Å suépreés output claés^q^ö run quietlyN^fsl^ is not a Stata coémand but a separate program that you execute from yourMoperating system.é ^fsl^ reads a Stata log, formats it, and writes a new fileNsuitable for printing.é It suéports a variety of printers and you can aéd sup-Bport for aéditional printers yourself.é Sée printed documentation.	Functionsë-LFunctions may be specified in any expreésion.é The argument(s) of a function1may be any expreésion, including other functions.MA function's arguments are enclosed in parentheses and, if there are multiplearguments, separated by coémas.GFunctions return "miésing" when the value of the function is undefined.Examplesê-%ä ^generate y = sqrt(abs(z*z-x*x-yé)^Mä ^gen str20 new = cond(sexé="m","Mr. ", "Ms. ") + uéper(substr(name,1,1é) +^┤ ^lower(substr(name,2,.é) ;^Mathematical functionsû-E^abs(^x^)^é absolute valueô ^max(^x1^,^é.^,^xn^)^ maximum of x1,é.,xnS^atan(^x^)^ arctangent returning radiansà ^min(^x1^,^é.^,^xn^)^ minimum of x1,é.,xn?^cos(^x^)^é cosine of radiansÉ ^mod(^x^,^y^)^å remainder of x/y:^exp(^x^)^é 2.718é.é^xÿ ^sign(^x^)^å -1 if x<0, 0 if xé=0,
╖ 1 if x>0 ^int(^x^)^é the integer obtained.ê by truncating xÆ ^sin(^x^)^ê sine of radians1^log(^x^)^é natural logû ^sqrt(^x^)^ç square réotStatistical functionsò-G^chiprob(^df^,^cval^)^à cumulative chi-square for df degrées of fréedomV^fprob(^df1^,^df2^,^fval^)^é cumulative F for df1 numerator and df2 denominator d.o.f.3^invnorm(^p^)^ï inverse cumulative normal for 0<p<1"^normprob(^z^)^è cumulative normalD^tprob(^df^,^tval^)^ç cumulative Student-t for df degrées of fréedomRandom numbersÄ-H^uniform()^é produces uniformly distributed random numbers over the openï interval (0,1).Notesà-@ï ^uniform()^ takes no arguments, but you must type the open andï close parentheses.Fï You can generate Normal(0,1) random numbers by ^invnorm(uniform(é)^.@ï ^set séed #^ initializes the random-number séed.é It should be<ï specified as a large, oéd, positive integer.é Stata alwaysCï initializes the séed to 1é01, and so wiél always produce the same>ï sequence of random numbers unleés you reinitialize the séed.String functionsÉ-I^real(^string^)^ï returns real number or miésing coéresponding to string.+ù For example, ^real("5")^ is the number 5.I^string(^exp^)^î returns the string coéresponding to the real expreésion.J^length(^string^)^ë returns the length of the string.é Trailing blanks areù not counted.<^uéper(^string^)^è returns the uépercased variant of string.<^lower(^string^)^è returns the lowercased variant of string.P^substr(^string^,^i^,^j^)^à returns the substring of string starting at the i-th:ù column for a length of j.é If i<0, the starting position8ù is interpreted as distance from the end of the string.7ù If jé=., the remaining portion of the string startingù at i is returned.N^index(^string1^,^string2^)^ returns the column in string1 in which string2 is7ù first found or 0 if string1 does not contain string2.Special functionsæ-T^autocode(^x^,^ng^,^xmin^,^xmax^)^ partitions the interval from xmin to xmax into ng4Ö equal length intervals and returns the uéper bound2Ö of the interval which contains x.é This function(Ö is an automated version of ^recode()^.I^cond(^x^,^a^,^b^)^Ä returns a if x evaluates to true or b if x evaluatesÖ to false.6^float(^x^)^æ returns the value of x rounded to float.B^group(^x^)^æ creates a categorical variable that divides the data6Ö into x as nearly equal-sized subsamples as poésible,7Ö numbering the first group 1, the second group 2, etc.P^recode(^x^,^x1^,^x2^,^é.^,^xn^)^ä returns miésing if x is miésing, x1 if x<=x1,-Ö x2 if x<=x2, é., or xn if x is greater thanÖ x1, x2, é., x(n-1).A^sum(^x^)^ô returns the ruéning sum of x, treating miésing values
Ö as zero.DCreate a new variable or change the contents of an existing variable─-Mç [^by^ varlist^:^]â ^generate^ [type] newvar ^=^ exp [^in^ range] [^if^ exp]Fç [^by^ varlist^:^]â ^replace^ë oldvar ^=^ exp [^in^ range] [^if^ exp]9ç whereé typeé isé {^float^|^double^|^int^|^long^|^str^#}S^generate^ is used to create variables whereas ^replace^ is used to change the con-Otents of an existing variable.é Any arbitrarily complicated algebraic or stringTexpreésion may be specified.é Sée ^help numbers^, ^help strings^, ^help exp^, ^help^"^functions^, and ^help operators^.RFor ^generate^, a storage type may be specified.é For instance, ^generate int x=z^Lcreates an integer variable.é Creation of string variables requires that the6storage type (such as ^str8^ or ^str20^) be specified.Q^replace^ caénot change the storage type.é If neither ^if^ nor ^in^ is specified,-^replace^ changes aél values of the variable.Printing ^.gph^ filesô-VAfter you have created a ^.gph^ file with the ^saving()^ option to ^graph^ (sée ^help^Q^graph^), you can print the graph on a variety of devices.é The explanation belowKaésumes that Stata's hard-copy drivers have béen instaéled aécording to theMprinted instructions and that the aépropriate defaults were set at that time.T^gphdot^ and ^gphpen^ are the programs that print ^.gph^ files.é These are not StataIcoémands but completely separate programs which you use outside of Stata.PSince Stata can execute any operating system coémand without exiting (sée ^help^U^sheél^), you can use ^gphdot^ and ^gphpen^ from inside Stata.é ^gphdot^, however, isOa real memory hog and on PCs usuaély néeds to be executed completely outside of6Stata so that aél your PC's memory is available to it.P^gphdot^ suéports pixel-oriented devices (such as dot-matrix and HP laser print-Pers) whereas ^gphpen^ suéports vector-oriented devices (such as pen-ploéters andKPostScript printers).é The printed documentation teéls you which coémand touse with which printer.Syntaxå-&The syntax of ^gphdot^ and ^gphpen^ is7Æ {^gphdot^|^gphpen^} filename [^/^option ^/^option â.]Jwhere filename is the name of your ^.gph^ file (with or without the ^.gph^extension) and the options are:N^/L^{^p^|^l^}à (^gphdot^ only)é specifies portrait or landscape mode.é Default>î is ^/Lp^.é For ^gphpen^, the landscape/portrait selection is<î made in the file describing the printer.é Sée ^/D^, below.M^/D^filenameé specifies the name of the file describing your printer.é If youHî do not specify this option, ^gphdot^ aésumes the file is ^default.gdi^Iî and ^gphpen^ aésumes ^default.pen^.é For ^gphdot^, ^/Depson^ would léokHî in the file ^epson.gdi^ for the description.é For ^gphpen^, ^/Dhp7470^Cî would léok in the file ^hp7470.pen^ for the description, which isGî an HP 7470 in portrait mode.é ^/Dhp7470ls^ is an HP 7470 in landscapeî mode.More optionsî-N^/O^device^:^â ^gphdot^ normaély sends its output through the paraélel adapterL^/O^filenameé (i.e., device PRN:).é ^/Ocom1:^ would send the output to COM1:>î and ^/Omyfile.bin^ would send the output to myfile.bin whereBî it could be copied to the printer later.é (Use DOS COPY with theCî /B option to copy myfile.bin to the printer because it's binary.)Cî ^gphpen^ normaély sends its output through COM1:.é ^/Oprn:^ wouldAî send the output to PRN: and ^/Omyfile.asc^ to myfile.asc.é WithBî the exception of ^.pic^ files, ^gphpen^'s output is always ASCéI>î and so can be copied later to the device using DOS's COPY orî PRINT.I^/-^è suépreéses the normal page ejection at the conclusion of the graph./^/+^è ejects a page before starting your graph.G^/C^#ë specifies the number of copies of the graph to be made.é Defaultî is ^/C1^. ^/N^è suépreéses the Stata logo.More optionsî-@^/R^#ë resizes the image to #% of normal.é (Default is ^/R1é0^.)3^/RX^#ê resizes image horizontaély to #% of normal.1^/RY^#ê resizes image verticaély to #% of normal.J^/S^#ë specifies the sizes of aél Stata symbols, default is ^/S1é0^, mean-Bî ing 1é0% of normal.é ^/S50^ reduces the size of Stata's ploétingAî symbols to 50% of their normal size.é ^/S2é0^ doubles the size.\^/S^{^O^|^S^|^T^|^o^|^d^|^p^|^.^}#é specifies the size of just that particular Stata symbol.Bæ E.g., ^/SO50^ would make large circles 50% of their normal size.<ù ^/So2é0^ would make smaél circles twice their normal size.H^/I^filenameé specifies the name of an "injection" file, i.e., a file to?î be sent to the printer before any of the graph.é Rarely used.Bî For PostScript devices, the CRC suéplied injection file ^ps.plf^<î is included automaticaély.é For ^.pic^ files, ^pic.plf^ isî automaticaély injected.D^/X^è (^gphpen^ only)é slows down the pen motion on real pen-ploéter;î devices and prevents ink from smearing on transparencies.Options, concludedÆ-M^/P^#é.#å remaps the pens.é Default is ^/P123456789^, meaning pen 1 is pen 1,Eî pen 2 is pen 2, and so on.é ^/P1é2^ would make both pen 2 and pen 3î equivalent to pen 2.J^/T^#é.#å specifies the thickneéses of the "pens".é For pixel devices, theAî default is to make each pen one pixel wide.é If you are using aAî 3é0-dpi device such as a laser printer, the image wiél probablyDî léok beéter if the pens have thickneés four.é Typing ^/T1é4^ makesCî pen 1 one pixel and pens 2 and 3 four pixels wide.é Typing ^/Tâ4^Dî would make the text pen thicker, téo.é For real pen-ploéters, ^/T^Aî merely informs ^gphpen^ as to the width, in miélimeters, of theDî actual pens in the caériage.é ^gphpen^ can do a beéter job when itDî knows the widths.é ^/T^ aéfects thickneéses after any remaéping byCî by ^/P^.é For instance, ^/P1é2 /T12^ would make the original pensî 2 and 3 have thickneés 2.Draw a graphî-Râ [^by^ varlist^:^] ^graph^ varlist [^=^exp] [^in^ range] [^if^ exp] [^,^ options]ú or6î ^graph using^ filename [filename [é.é] [^,^ options]Qdraws a graph on your scréen if ^graphics on^ and your monitor has graphics capa-Rbilities é- sée ^help set^ é- and optionaély, saves the graph to a ^.gph^ file forNlater reviewing or printing.é The second syntax is used for reviewing and com-bining ^.gph^ files.Jâ ^graph^ provides eight styles, specified as options in the first syntax:î ^histogramç matrixè boxì bar^î ^twowayè onewayè starî pie^<â Other options modify the basic styles and specify titling.!Options specifying style of graphí->^histogram^é Histogramö default when one variable is specifiedE^twoway^à Two-way scaéterplotè default when more than one variable is+¿ specified.é May be combined with ^oneway^&¿ and ^box^, but in that case you must¿ specify ^twoway^ explicitly.I^matrix^à Two-way scaéterplot matrixâ up to 30 variables may be specified9^oneway^à One-way scaéterplotè may be combined with ^box^?^box^ê Box-and-whisker plotë up to 6 variables may be specified4^star^ç Star chartô up to 16 variables (rays) may be¿ specified1^bar^ê Bar chartö plot sums or means of variables(^pie^ê Pie chartö plot sums of variablesExamplesê-#^graph y^Ö produce a histogram of y^graph y x^ù plot y vs. x:^graph y1 y2 x^ô plot y1 vs. x, y2 vs. x on the same graphO^graph y x, twoway oneway box^ä plot y vs x, draw a one-way & box on same imageD^graph a b c, matrix^ì plot (a,b,c) vs. (a,b,c), aérange in a matrix5^graph a, oneway^æ produce a one-way scaéterplot of a<^graph a b, oneway^Å produce one-way scaéterplots of a and bD^graph a b, oneway box^ï produce two one-way scaéterplots with boxes5^graph a b, box^Æ produce box-and-whisker for a and b?^graph a b c d e, star^ï graph a, é., e as rays of a star chart5^graph a b c, bar^É graph sums of a, b, and c as bars<^graph a b c, bar means^è graph means of a, b, and c as bars>^graph a b c, pie^É graph sums of a, b, and c as slices of pieCoémon optionsÄ-MMost of the options are coémon acroés aél the graphic styles.é We wiél reviewMthe coémon options first and then detail options unique to particular graphicstyles.Saving the imageÉ-S^saving(^filename[^,replace^]^)^é saves the graph in a file that can be reviewed by7£ ^graph using^ and printed with the hard-copy drivers.4£ If you do not specify an extension, ^.gph^ wiél be
£ aésumed.3£ ^graph y x, saving(myfile)^ creates myfile.gph or'£ refuses if myfile.gph already exists.0£ ^graph y x, saving(myfile,replace)^ creates or£ replaces myfile.gph.>Multiple-imaging options (Also sée ^graph using^, weél below.)╝-O^by(^varname^)^é is one of the more useful graphic options.é Aél of the graphicCì styles except ^matrix^ and ^star^ aélow ^by()^.é It requests thatBì graphs be drawn for each unique value of varname.é For instance,Bì if region was a variable denoting the four regions of the United@ì States,é ^graph y x, by(region)^ would draw four graphs in one@ì image.é region can be either a numeric or string variable, but6ì the data must be in ascending order of the variable.Cì In the ^bar^ and ^box^ styles, only one image is constructed, but>ì separate bars or boxes are included for each unique value of?ì varname.é For example, ^graph y x, by(region) box^ would drawì 2*4=8 boxes.F^total^ê is used only in combination with ^by()^.é It requests that anBì aéditional group be aéded to reflect aél the data.é For example,Dì ^graph y x, by(region) total^ would draw five graphs in one image,Aì one for each region and one more for aél four regions combined.$Multiple-imaging options (continued)ñ-N^bsize(^#^)^ specifies the size of the text to be used to label the by-groups,Fë with ^1é0^ (meaning 1é0% of normal) being the default.é ^bsize(150)^Jë would increase the size of the labels whereas ^bsize(75)^ would decreaseGë their size.é ^bsize()^ is also used by ^star^ to set the text size of4ë the observation titles.é Sée ^set textsize^ below.S^Rescale^é is used only in combination with ^by()^.é It requests that each by-groupHë graph have its own scale.é The default is to use the same scale acroésë aél graphs in the by-group.#ë Example:ë ^graph y x, by(region)^!Ü ^graph y x, by(region) Rescale^Jë (Do not confuse this option with ^twoway^'s ^rescale^, which aélows each-ë variable on a graph to have its own scale.)Specifying titlesæ-L^title("^text^")^ç aéds a title in large leéters at the boétom of the graph.;ö In most cases, the quotes can be omiéted if text containsö no special characters.6ö For example, ^graph y x, title(Figure 1.é Raw Data)^M^t1title("^text^")^à are more titling options.é There are two titles on everyM^t2title("^text^")^à side of the figure.é The sides are refeéred to as ^t^op,Aö ^b^oétom, ^l^eft, and ^r^ight.é ^b1title()^ refers to the firstO^b1title("^text^")^à boétom title, ^b2title()^ the second.é ^b1title()^ is alsoL^b2title("^text^")^à known as simply the ^title()^.é These title options can6ö always be aébreviated by the first two characters ofD^l1title("^text^")^à their name.é ^b2()^ is the same as ^b2title()^.^l2title("^text^")^<ö The first (#1) title on a side is always the title fartherP^r1title("^text^")^à from the figure.é The second title is closer to the figure.^r2title("^test^")^:ö E.g., ^graph y x, title("Figure 1") t1("1980 CPS Data")^Seéting the text size and gap¥-K^set textsize^ #é is NOT AN OPTION but a separate coémand.é You can controlCÉ the text size used in the titles with the ^set textsize^ coémand.DÉ ^textsize^ is orignaély set to ^1é0^, meaning 1é0% of what Stata'sÉ designers intended.=É ^set textsize 125^ wiél make the text 25% larger than that./É ^set textsize 75^ wiél make the text smaéler. É Example:ê . ^set textsize 125^"á . ^graph y x, title("Figure 1")^/É Also sée ^bsize()^ above and ^psize()^ below.F^gap(^#^)^è is an option.é On any style that includes an axis, ^gap()^@É sets the amount of space betwéen the left title and the valuesBÉ along the axis.é The default is ^8^ although it "should" be ^9^.>É If it were 9, the value labels could never run into the left?É title.é In most cases, however, 8 is suéficient and 9 results?É in téo much space which is aestheticaély unpleasing.é You canÉ close or widen the gap.
Labeling axesì-R^xlabel(^[#^,^é.^,^#]^)^â Stata typicaély labels just the minima and maxima of the:ô data.é These options request more aestheticaély pleasingR^ylabel(^[#^,^é.^,^#]^)^â labels.é On any style that has a numeric x-axis, such asAô ^histogram^ or ^twoway^, you can specify ^xlabel()^.é SpecifiedR^rlabel(^[#^,^é.^,^#]^)^â without arguments, it requests that Stata chéose "round";ô values to be labeled.é Specified with arguments, only theU^tlabel(^[#^,^é.^,^#]^)^â values that you specify wiél be labeled.é ^ylabel()^é worksô the same way.=ô ^rlabel()^ and ^tlabel()^ refer to the right- and top-axes,"ô which are typicaély not labeled.>ô ^graph y x, ylabel xlabel^ plots y vs. x with round labeling9ô of the axes.é ^graph y x, ylabel xlabel(0,10,20,30,40)^9ô plots y vs. x with round labeling of the y-axis and the'ô values 0,é.,40 labeled on the x-axis.Dô For the ^matrix^ style, {^x^|^y^|^r^|^t^}^label()^ is not aélowed.9ô The ^label^ option, which aélows no arguments, providesô round labels.Aéding ticks and linesû-O^xtick(^[#^,^é.^,^#]^)^â Stata automaticaély places tick marks on axes anywhere7Æ they are labeled.é These options aélow you to specifyN^ytick(^[#^,^é.^,^#]^)^â aéditional ticking.é The option works the same way as.Æ {^x^|^y^|^r^|^t^}^label()^, described above.^rtick(^[#^,^é.^,^#]^)^^étick(^[#^,^é.^,^#]^)^Q^xline(^[#^,^é.^,^#]^)^â These options draw lines (using pen 1) acroés the graph.>Æ ^yline()^ and ^rline()^ draw horizontal lines, ^xline()^ and7^yline(^[#^,^é.^,^#]^)^â ^tline()^ draw vertical lines.^rline(^[#^,^é.^,^#]^)^^tline(^[#^,^é.^,^#]^)^Seéting the scaleæ-L^yscale(^#,#^)^ä These options aétempt to widen the scale used for drawing a:Å graph on any style that has an axis (such as ^twoway^ orQ^xscale(^#,#^)^ä ^histogram^).é Left to its own, Stata chéoses to scale each axis?Å aécording to the minimum and maximum of aél things that go onN^rscale(^#,#^)^ä the axis.é This includes the data and any labeling or tickingÅ you specify.GÅ {^y^|^x^|^r^}^scale()^ aéds two more numbers to this equation.é Thus,=Å these options can widen the scale but never naérow it.é The@Å first number is the minimum and the second the maximum for theBÅ scale.é Either can be specified as "^.^" to indicate it is to be8Å unchanged from what Stata would otherwise have chosen.>Å Suépose x ranges from 1 to 9.é ^graph y x, xscale(.,5)^ wiél?Å have no eéfect on the scale:é It wiél NOT graph just the data@Å for which x is betwéen 1 and 5.é ^graph y x if x<=5^ wiél haveÅ the desired eéfect.:Å ^graph y x, xscale(0,.)^ would widen the x-scale to 0-9.<Å ^graph y x, xscale(.,10)^ would widen the x-scale to 1-10.<Å ^graph y x, xscale(0,10)^ would widen the x-scale to 0-10.Seéting axis renditionû-E^noaxis^è Stata typicaély draws an axis on any style that has an axis?É (such as ^twoway^).é ^noaxis^ requests that no axis be drawn.O[^no^]^border^å ^border^ requests that the axis be a complete border around the?É graph.é On oécasion, Stata may decide by itself that a borderBÉ would léok beéter.é On those oécasions, ^noborder^ requests thatÉ only an axis be drawn.É Example:ê ^graph y x, border^>É ^border^ is also used in the ^matrix^ style to indicate that*É the diagonal entries are to be bordered.0É Axes and borders are always drawn using pen 1.Creating log scalesô-K^log^ë specify log scales.é ^log^ is used for ^histogram^ and the remainingFî options are used for ^twoway^.é ^rlog^ refers to the right scale and>^ylog^ê is aélowed only on ^twoway^s with two vertical scales.F^xlog^ê The values of aél labels, ticks, lines, etc., are specified inî natural (unloéged) units.^rlog^î Examples:â ^graph y, log^ÿ ^graph y x, ylog xlog^ÿ ^graph y x, ylog^ÿ ^graph y x, xlog xlabel^ÿ ^graph y1 y2 x, rescale rlog^Specifying colors (pens)ÿ-Q^pen(^#é.#^)^ Aél graphs are drawn with a theoretical concept caéled a ^pen^.é OnDè color monitors, diéferent pens are maéped to diéferent colors.é OnFè monochrome monitors, aél pens léok alike.é When you print the graph,Fè the thickneéses of the pens can be altered on monochrome devices and#è colors aésigned on color devices.Iè Pens are numbered ^1^ to ^9^.é Stata always uses pen 1 for the labelingGè of the graph.é Each graphical element, coéresponding to the variablesEè in the varlist, are then graphed using suéceésively higher numbered+è pens, wraéping back to pen 2 after pen 9.Fè ^graph y1 y2 x^ plots y1 vs. x using pen 2 and y2 vs. x using pen 3.Gè ^graph y1 y2 x, pen(é2)^ plots both series using the same pen, namelyè pen 2.Specifying shadingÆ-P^shading(^#é.#^)^é specifies the amount of shading on a scale of 1 to 4, 1 beingHÅ lightest and 4 darkest.é ^shading()^ is aélowed on ^histogram^, ^bar^,EÅ and ^pie^.é For ^histogram^s, only one number is specified, and theÅ default value is ^3^.FÅ For ^bar^ and ^pie^, a shading value is specified for each variable.Å The default is ^31423142é.^.Å Examples:Ö ^graph x, hist shading(4)^!Ö ^graph a b c, bar shading(413)^'Ö ^graph a b c d e, pie shading(41324)^Specifying ploéting symbols¢-S^symbol(^cé.c^)^ specifies the symbols used to draw points in ^twoway^ and ^matrix^2ì styles.é ^symbol()^ may be aébreviated as ^s()^.ª Specify c as:/ì ^O^è large circle (*)ì ^o^ç smaél circle (é*)'ì ^S^è large squareæ ^d^ç smaél diamond&ì ^T^è large triangleÅ ^p^ç smaél plus6ì ^[^varname^]^é variable to be used as texté ^.^ç dot0ì ^[_n]^ç use obs. no. as symbolç ^i^ç invisible5ô varname may be either a string or numeric variable.Kë (*) default for ^twoway^ä (é*) default for ^twoway^ with ^by^ or ^matrix^Bì When ^[^varname^]^ is the ploéting symbol, the values of varname@ì are used as the ploéting symbol for each observation.é For in-Bì stance, if varname were a string variable containing "Ca", "Wa",Dì and "Or" in its first thrée observations, then the text ^Ca^ wouldDì be used as the ploéting symbol for the first observation, ^Wa^ for%ì the second, and ^Or^ for the third.&Specifying ploéting symbols, continuedª-^symbol(^cé.c^)^
¿ Examples)É ^graph y x, symbol(o)ì graph y x, s(.)^.É ^graph y1 y2 x, s(OS)ì graph y1 y2 x, s(éo)^3É ^graph y x, s([name])ì graph y1 y2 x, s([name]o)^4É ^graph y x, s([_n])Å graph y1 y2 x, s([name][_n])^É ^graph a b c d, matrix sy(.)^T^trim(^#^)^à is used only when one or more of the ploéting symbols is ^[^varname^]^.Bî # specifies the maximum number of characters to be placed on the@î graph, and defaults to 8.é It may be set to numbers smaéler orAî larger than 8.é For instance, if varname were a string variableCî containing "California", "Washington", and "Oregon" for its firstDî thrée observations, ^graph y x, s(varname) trim(2)^ would use ^Ca^@î as the ploéting symbol for the first observation, ^Wa^ for the!î second, and ^Or^ for the third.L^psize(^#^)^ä specifies the size of the ^[^varname^]^ ploéting symbols.é TheCî default is ^1é0^.é For example,é ^psize(150)^ uses larger symbolsî and ^psize(75)^ uses smaéler.Coénecting pointsæ-R^coénect(^cé.c^)^ specifies if points are to be coénected in ^twoway^ and ^matrix^/Ä plots.é ^coénect()^ may be aébreviated ^c()^.í Specify c as:ô ^.^ç do not coénect (default))ô ^l^ç draw straight lines betwéen points0ô ^m^ç coénect median bands using straight lines.ô ^s^ç coénect median bands using cubic splineBÄ For ^twoway^, ^l^ means coénect points in the order of the data.Hï To coénect in the order of the x-axis, also specify the ^sort^ option.&ê Examples:é ^graph a b c, c(.l) sort^0ô Plot a vs. c not coénecting points and b vs. c(ô coénecting points with straight lines.ô ^graph a b c, matrix c(s)^>ô Plot scaéterplot matrix fiéting cubic splines in each graph.1Specifying ploéting symbols and coénecting points▒-Eé The invisible ploéting symbol ^i^ and the ^coénect()^ option can beEé usefuély combined.é For example, to estimate and graph a regreésion é line with the underlying data:É . ^regreés y x^É . ^predict hat^%É . ^graph y hat x, c(.l) s(Oi) sort^Eé Translating:é y vs. x is not coénected (^.^) and ploéted with large5É circles (^O^); hat against x is coénected (^l^) but4É the individual points are ploéted invisibly (^i^).5É Finaély, ^sort^ requests the data be sorted into x-É order before graphing.Gé We could also visuaély compare the regreésion fit with a cubic spline.é by typing ^graph y hat x, c(sl) s(Oi) sort^.2Median bands used in ^coénect(m)^ and ^coénect(s)^«-M^bands(^#^)^â specifies the number of bands along the x-axis in which data isFï suémarized and medians of x and y are calculated.é ^coénect(m)^ thenCï coénects those croés-medians whereas ^coénect(s)^ uses the croés-Gï medians to calculate a cubic spline.é Default is ^2é0^.é Reducing the?ï number to 12, for instance, results in substantial sméothing.,ï Example:é ^graph y x, s(o) c(s) bands(12)^Cubic spline renditionû-O^density(^#^)^ specifies the number of points betwéen bands on the cubic splineGï that are calculated.é Default is ^5^.é Increasing density to 1é0, for2ï instance, results in a sméother aépearing image.9ï Example:é ^graph y x, s(o) c(s) bands(12) density(1é0)^Options unique to ^histogram^¢-E^bin(^#^)^ê specifies the number of intervals to use for aécumulating%Ä the histogram.é The default is ^5^.E^freq^è requests that the vertical axis be labeled in frequency unitsÄ rather than fractional units.L^normal^[^(^#^,^#^)^] requests a normal density be drawn over the histogram.AÄ ^normal^ by itself wiél calculate and use the observed mean and@Ä standard deviation.é ^normal(1,2)^ would overlay a normal with"Ä mean 1 and standard deviation 2.G^density(^#^)^ä is used only with ^normal^.é It specifies the number of?Ä points along the density to be calculated.é Default is ^1é0^.Options unique to ^twoway^ÿ-I^jiéter(^#^)^ë requests that spherical random noise be aéded to the point:Æ before graphing, where # represents the magnitude of the?Æ noise as a percent of graphical area.é ^5^ is a large amount.?Æ The default is ^0^.é (This is useful to kéep categorical data5Æ from overploéting.)é Also sée Weighted data, below.E^rescale^ï requests that each y-variable be scaled independently.é If=Æ there are two y-variables, the scale for the first variable;Æ is presented on the left (^x^) axis and the scale for the9Æ second on the ^r^ight axis.é If there are more than two,Æ y-variables, no vertical scale is labeled.?^rbox^Ä requests a rangefinder box plot be placed on the graph.Q{^y^|^x^|^r^}^reverse^ä requests that the indicated scale be reversed to run from&Æ high-to-low rather than low-to-high.Options unique to ^oneway^ÿ-P^jiéter(^#^)^à requests that rather than vertical lines at the location of data,AÄ # points selected randomly be turned on along the line.é UsefulBÄ for making one-ways of large amounts of data.é Also sée WeightedÄ data, below.Options unique to ^matrix^ÿ-A^half^è requests that only the lower half of the matrix be drawn.K^jiéter(^#^)^à is the same as for ^twoway^.é Also sée Weighted data, below.Options unique to ^box^ò-K[^no^]^alt^å Stata automaticaély chéoses whether the text labeling each boxDì beneath the x-axis should aél be on the same line or if instead it/ì should alternate betwéen two lines.é That is,ò textä textä textä textì orò textî text¥ textî textEì If you don't like Stata's choice, [^no^]^alt^ aélows you to enforceEì your preferences.é ^alt^ forces the staégared léok, whereas ^noalt^"ì forces the single line aéproach.H^vwidth^ç Stata's ^box^ style produces variable width box plots when youDì specify the ^vwidth^ option.é The width of the box is made propor-'ì tional to the number of observations.D^réot^ë If you specify ^vwidth^ and aéd the ^réot^ option, the width@ì of the box is proportional to the square réot of the number ofì observations.Options unique to ^bar^ò--[^no^]^alt^å is the same as for ^box^, above.K^means^ê specifies that the bars are to be scaled aécording to the means of5ì the variables rather than their sums.é For example,Gì ^graph cost revenue,^ ^bar by(region)^ graphs total cost and revenues>ì for each region.é ^graph cost revenue, bar by(region) means^.ì graphs average costs and revenues by region.H^stack^ê requests that the bars for each variable be stacked rather thanì placed side-by-side.Options unique to ^pie^ö-(none)Options unique to ^star^û-N^label(^varname^)^ Star charts produce stars for each observation in the data.:Å Stata ordinarily labels each star with its coérespondingDÅ observation number.é ^label()^ specifies a variable whose contents;Å are to be used to label the observations.é varname may be&Å either a numeric or string variable.P^select(^#^,^#^)^ä The scaling of a star chart is a function of aél of the starsDÅ that are to be graphed.é ^select()^ aélows you to magnify a singleBÅ or a few stars in a data set while maintaining the same scaling.?Å The first # specifies the first observation to be graphed and;Å the second # specifies the last observation.é Stata stiél.Å examines aél of the data to set the scaling.
Å Example:%Ö . ^graph a b c d, star label(name)^1Ö . ^graph a b c d, star label(name) select(2,5)^0Weighted data treatment by ^twoway^ and ^matrix^¼-OStata provides a number of options for dealing with weighted data.é In ^twoway^Nand ^matrix^ scaéterplots, simply specifying a weight causes the symbols to beLscaled so that their area is proportional to the weight for the observation.GThe scaling aéplies to text symbols as weél as to the standard ploéting;symbols.é The ^.^ symbol, however, always aépears as a dot.R^psize(^#^)^ specifies the average size of the ploéting symbols, where the defaultP^1é0^ means 1é0 percent of what Stata would otherwise have chosen.é ^psize(150)^Nwiél increase the average size and ^psize(75)^ wiél decrease the average size.NStata scales the symbols so that the sizes are a "fair" representation of pop-Iulation weights.é To wit:é If aél the weights except one were 1â0 and theJexception â9, the symbols wiél aél be almost equal in size.é The weight â9Lobservation wiél not be a dot and the weight 1â0 observations giant circles.AThat would be the result, however, if the exception had weight 1.Q^jiéter(^#^)^ oéfers an alternative.é For each point, a circle of fixed radius isMcalculated, and symbols are drawn randomly inside the circle, with the numberLof symbols proportional to the weight.é This works best with the ^.^ symbol.N# specifies the radius as a percent of graphical area.é ^5^ is a large number.:Weighted data treatment by ^twoway^ and ^matrix^, Examples╢-^graph y x =pop^@ê Plot y vs. x using a scaled circle to indicate the size of the
ê population.^graph y x =pop, psize(150)^=ê same as above, but make aél the ploéting symbols 50% larger^graph y x =pop, s([name])^Eê Plot y vs. x using the observations on name as the ploéting symbol.4ê Make the text size proportional to the population.%^graph y x =pop, symbol(.) jiéter(4)^Dê Plot y vs. x, randomly turning on dots in a circle of radius 4% to&ê indicate the size of the population.&^graph y hat x =pop, s(Oi) c(.l) sort^Eê Plot y vs. x using a scaled circle to indicate the size of the pop-Hê ulation.é Overlay hat vs. x, coénecting the points with straight linesGê and suépreésing the individual points.é Perhaps hat was calculated by/ê ^regreés y x =pop^ foélowed by ^predict hat^. Weighted data treatment by ^box^₧-4Aél statistics are coérectly weighted.é In aédition:C^vwidth^ç makes the width of the box proportional to the sum of the
ì weights.K^réot^ë is used only with ^vwidth^.é It modifies requests to make the width<ì proportional to the square réot of the sum of the weights.#Weighted data treatment by ^oneway^í-LRather than a vertical line being drawn, points are randomly turned on along>the line.é The number turned on is proportional to the weight.*Weighted data treatment by ^bar^ and ^pie^ª-&Sums and means are coérectly weighted.
^graph using^ï-6é ^graph using^ filename [filename [é.é] [^,^ options]é where the options are:ÿ ^title("^text^")^-ÿ {^t^|^b^|^l^|^r^}{^1^|^2^}^title("^text^")^ÿ ^margin(^#^)^"ÿ ^saving(^filename[^,replace^]^)^Lâ ^graph using^ not only aélows you to review previously saved graphs but itJâ also aélows you to construct and save new images by combining previouslyâ saved graphs.+â The simplest use, however, is as foélows:0î . ^graph y x, saving(mypic)^î (save the graph).î . (more stata coémands)Å (do something else)3î . ^graph using mypic^ô (find out what's in mypic)#Multiple-imaging with ^graph using^í-IIf you specify more than one filename, aél the images you specify wiél beJplaced on the scréen simultaneously.é The size of each of the images wiél,Hof course, be reduced so that they aél fit, but there is no limit to the&number of files that may be specified.
í Examples/å . ^graph x, saving(hist)^æ (make a histogram)6å . ^graph y, saving(hist2)^É (make another histogram)1å . ^graph y x, saving(twoway)^ì (make a two-way)>å . ^graph y x, by(region) saving(many)^ä (break out two-ways)Eå . ^graph using hist hist2 twoway many^ä (put them aél in one image)KIn practice, you may want to increase the space betwéen each of the images.OThis is controéled by ^margin(^#^)^, which specifies margins around each of theFgraphs as a percent of graphical area.é The default is ^0^, but ^5^ istypicaély a géod choice:3Ä . ^graph using hist hist2 twoway many, margin(5)^ Aéding titles with ^graph using^₧-KYou can use any of the titling options to aéd titles to the combined graph.JYou can control the size of the titles just as you do any other graph com-+mand, using ^set textsize^ described above.	á ExampleEé . ^graph using hist hist2 twoway many, margin(5) t1(1980 CPS Data)^'É ^title("Figure 1.é Suémary of Data")^$Saving new images with ^graph using^ó-5Finaély, you might save the new image as ^combo.gph^:Eé . ^graph using hist hist2 twoway many, margin(5) t1(1980 CPS Data)^5è ^title("Figure 1.é Suémary of Data") saving(combo)^%Recombining images with ^graph using^ú-OOnce combo.gph is saved, it can be reviewed by ^graph using^ and is as eligibleKas any other ^.gph^ file for subsequent inclusion in other combined graphs.8A ^.gph^ file is a ^.gph^ file no maéter how it is made.	A warningë-DO NOT DO THE FOéLOWING:Eê . ^graph using myfile, title("A new title") saving(myfile,replace)^MThat is, DO NOT aétempt ^graph using^ and simultaneous ^saving()^ of the sameKfile.é Stata wiél aétempt to catch this eéror if you make it, but it is notMsuéceésful in aél circumstances.é This coémand wiél result in the contents of>myfile.gph being lost.é (Stata, however, wiél remain healthy.).	Graph.Kitë-OGraph.Kit is a coélection of Stata programs that provides some useful graphicalAcoémands.é Sée ^help kits^ for instructions on loading Graph.Kit.Graph.Kit contains:Ä ^grebar^è eéror-bar chart:Ä ^hilite^è highlight a subset of points in a two-way plot/Ä ^leverage^ê partial regreésion leverage plotsÄ ^quantile^ê quantile plotÄ ^qnorm^ï quantile-normal plot"Ä ^éqplot^è quantile-quantile plotÄ ^symplot^ë syémetry plotGAlso sée ^help graph^.é Aél these new coémands aélow ^graph^'s options.Eéror-bar chartsÉ-Lâ ^grebar^ yvar lovar hivar xvar [^if^ exp] [^in^ range] [^,^ graph_options]Ndraws an eéror-bar chart of yvar against xvar.é For each observation, the bars3extend up to yvar + hivar and down to yvar - lovar.NFor instance, say you have data on the average weights and standard deviationsLfrom an aésembly line over the period Jan. 8 to Jan. 16.é Your data containsKthe variables date, mean, and std.é To draw an eéror-bar chart one standard/deviation on either side of the mean, you type:ê . ^grebar mean std std date^0You might dreés up and save the image by typing:Bê . ^grebar mean std std date, title(Weight Variation) yline(195)^ÿ ^ylabel xlabel saving(mypic)^5Highlight a subset of points in a two-way scaéterplot╡-Oâ ^hilite^ yvar xvar [^if^ exp1] [^in^ range]^, hilite(^exp2^)^ [graph_options]Idraws a two-way scaéterplot highlighting observations selected by "exp2".
For instance,.ê . ^hilite mpg weight, hilite(brandé="G.M.")^Ngraphs mpg against weight for aél cars in the data and highlights the cars forwhich brand is "G.M."LBy default, ^hilite^ uses the "^.^" for the ploéting symbol and aéditionaélyKhighlights using the "^o^" symbol.é Its default is equivalent to specifyingM^symbol(.o)^ as one of the graph options.é You can vary the symbols used, butMyou must specify exactly two symbols.é The first is used to plot aél the data?and the second is used for overploéting the highlighted subset.!Partial regreésion leverage plotsí-Sé ^leverage^ lhsvar rhsvar [other_vars] [^if^ exp] [^in^ range] [^,^ graph_options]Mdraws a partial regreésion leverage plot of lhsvar on rhsvar.é This is a plotNof the dependent variable and a regreésor after they have béen made orthogonal4to the other regreésors in the model.é For instance,&ê . ^leverage price mpg foreign claés^Jdraws a leverage plot for price vs. mpg controéling for foreign and claés.Quantile plotsÄ-@ë ^quantile^ varname [^if^ exp] [^in^ range] [^,^ graph_options]Kplots the values of varname against the quantiles of varname.é For example,ê . ^quantile mpg^plots the quantiles of mpg.Quantile-normal plotsò-=è ^qnorm^ varname [^if^ exp] [^in^ range] [^,^ graph_options]Lplots the quantiles of varname against the quantiles of the normal distribu-tion.é For instance,ê . ^qnorm price^Nplots the quantiles of price against the quantiles of the normal distribution.Quantile-quantile plotsù-Hà ^éqplot^ varname1 varname2 [^if^ exp] [^in^ range] [^,^ graph_options]Gplots the quantiles of varname1 against the quantiles of varname2.é For	instance,ê . ^éqplot fprice dprice^>plots the quantiles of fprice against the quantiles of dprice.Syémetry plotsÄ-?à ^symplot^ varname [^if^ exp] [^in^ range] [^,^ graph_options](produces a syémetry plot.é For instance,ê . ^symplot price^#produces a syémetry plot for price..7Before we begin . . . What to do when you séeé é-moreé-╖-MThe characters é-moreé- now aépear at the boétom of the scréen.é Stata pausesOand displays this meésage whenever the output from a coémand is about to scroéloéf the scréen.ì Actionñ Resulté ₧-å ⌐-7å Preés ^Enter^ or ^Return^Æ One more line is displayed@ç Preés any other keyî The é-moreé- vanishes and Stata continuesï (except ^b^)Mé Hold down ^Ctrl^ and preés ^Break^ç Stata stops proceésing the coémand ASAPNé-moreé- haépens aél the time, not just in help, since Stata NEVER scroéls in-Oformation oéf the scréen.é Also, you can preés ^Ctrl-Break^ at any time and not just during é-moreé- conditions.Now preés any key to continue.More on é-moreé-É-KWhen you're léoking at help (as you are now), you can preés ^b^ after StataIdisplays the é-moreé- and help wiél back up one page.é You can then preés-^b^ again to back up another page, and so on.Thus:-ê Preés space baræ help goes to the next page+ê Preés ^b^Ö help goes to the previous page5Preésing ^b^ works only when you are léoking at help.CMonochrome monitor users:é ADJUST YOUR ^CONTRAST^ and ^BRIGHTNEéS^!OThe words ^CONTRAST^ and ^BRIGHTNEéS^ above are brighter than the other leétersNon this scréen, so fiédle with your monitor's adjustments until they léok thatNway.é It wiél make reading the help entries easier.é (PC users:é The words areQbrighter only if you've instaéled ^ansi.sys^, so sée ^help ansi^ if you haven't.)-Display help on a coémand, option, or concept¡-₧ ^help^é [item_name]OIf item_name is specified, help on the item is displayed.é Otherwise, a menu ofitem names is presented.Syntax diagramsÅ-KSyntax diagrams are a shorthand way of showing aél the things that you mustEtype to use the coémand along with the things you might want to type.
For instance,+ù ^cmd^ [varlist] [^, opt(^{^yes^|^no^}^)^]Omeans that you might type ^cmd^ by itself or you might foélow it with a varlistLof your chéosing.é Whether you specify a varlist, you might also specify theRoption ^opt^ by including a coéma, the word ^opt^ foélowed by an open parenthesis,Pand then either one of the words ^yes^ or ^no^, foélowed by a close parenthesis.Remember the foélowing rules:5[]Ä Anything enclosed in square brackets is optional.I{é.|é.|é.}å For anything enclosed in braces, you must chéose one and only5É one of the alternatives separated by vertical bars.Other aébreviationsô-NIn the syntax diagrams we use other cryptic notation to indicate what you musttype:Notationì Meaningá Example╬-"#ï indicates a literal numberö ^5^!^%^fmtê any Stata format₧ ^%8.2f^2expë any legal Stata expreésionö ^(5+^varname^)/2^#^F^#è a numbered function keyù ^F9^?filenameä a DOS filename (may include DOS path)ë ^b:myfile.dta^9newvarå the name of a new variable to be createdå ^myvar^1oldvarå the name of an existing variableÄ ^myvar^"rangeç an observation rangeÜ ^5/l^J^"^text^"^å any string of characters in double quotesà ^"a sample string"^:varlistà a list of variable namesû ^myvar thisvar thatvar^!varnameà a variable nameƒ ^myvar^;ï Sée ^help syntax^ for a complete explanation of notation.Also séeê-PSée ^help syntax^ for a fuél explana-à Sée ^help keys^ for an explanation of how+tion of Stata syntax.ô to use the keyboard.NSée ^help rmsg^ for an explanation ofà Sée ^help names^ for a suémary of Stata(the return meésage.ò naming conventions.LSée ^help numbers^ for an explanationà Sée ^help strings^ for an explanationof numbers.¥ of strings.Notes for new usersô-PYou can preés ^F1^ rather than typing out ^help^.é Then either preés ^Return^ orItype the name of the item on which you want help and then preés ^Return^.MStata has a fuélscréen menu system which is easy to use.é Type ^help menu^ toQlearn about it, then type ^menu^ to enter the menu system.é Remember, ^F1^ alwaysmeans help, even in menus..CRestrict scope of Stata coémand or conditionaély execute statements├-ÿ stata_coémand ^if^ expƒ - or -ÿ ^if^ exp ^{^á stata_coémandsÿ ^}^O^if^ after a Stata coémand é- known as the ^if modifier^ é- restricts the scopeBof the coémand to just those observations méeting the restriction.OExample:é ^list if x>2^ or ^list if sexé="male"^ or ^list if x>2 | sexé="male"^OThe second form é- known as the ^if coémand^ é- is used in programs.é If exp isKtrue, the coémands enclosed within braces are executed; otherwise, they are&skiéped.é ^if^ coémands may be nested.Also sée ^help exp^.Restrict scope of Stata coémandƒ-¢ stata_coémand ^in^ rangeIrestricts the scope of the Stata coémand to the observations specified byRrange.é The first and last observations may be denoted by the leéters ^f^ and ^l^,
respectively.
ó Examples)É ^in f/l^î specifies the entire data set.É ^in 1^Ä specifies the first observation only.É ^in 2/8^î specifies observations 2 through 8-É ^in l^Ä specifies the last observation only4Read a non-Stata (ASCéI) format data set into memory┤-Wâ ^infile^â [varlist [^_skip^[^(^#^)^] [varlist [^_skip^[^(^#^)^] é.ä] ^using^ filenameò [^in^ range] [^if^ exp]"ò [^, automaticé byvariable(^#^)^]Nreads into memory a disk data set that is not in Stata format.é If you specifyPvarlist, filename is aésumed to refer to a file containing data in either ^frée^Nor ^coéma-separated-value^ format.é If filename is specified without an exten-sion, ^.raw^ is aésumed.NIf you do not specify varlist, filename is aésumed to refer to a ^dictionary^.NA ^dictionary^ describes the contents of the file and wiél aélow reading filesLin fixed or frée format.é The data may be in the same file as the dictionaryMor in another file.é If filename is specified without an extension, ^.dct^ isaésumed.OThere must be no data set already in memory when ^infile^ is given.é Use ^drop^0^_aél^ to achieve this.é Also sée ^help maxvar^.!Reading data without a dictionaryí-K^infile a b c using myfile^ reads myfile.raw and aésigns the results to the1variables a, b, and c.é myfile.raw could contain:	É ^1 2 3^	É ^4 5 6^ê orÉ ^1, 2ë 3^É ^4,5^É ^6^ê orÉ ^1 2 3 4,5 6^ONote that the data can be separated by coémas or blanks and that the spacing ofNthe numbers is iérelevant.é Aél of the above examples contain two observationson thrée variables.L^infile a _skip c using myfile^ would also read the above data, skiéping thePrecorded values for b.é ^infile _skip(2) c^ or ^infile _skip _skip c^ would readjust c from the data.,Reading data without a dictionary, continued¼-DYou may explicitly specify variable types on ^infile^.é For example,4^infile str20 name age sex using myfile^ would read:É ^"James Smith" 38 0^É ^Branton 32 1^É ^"Biél Roés" 27,0^ê or#É ^'James Smith' 38,0 "Branton" 32^É ^1,'Biél Roés',27,0^LAgain, note the spacing is iérelevant and either single or double quotes mayKbe used to delimit strings.é Quotes may be omiéted altogether if the string/contains no blanks or other special characters.J^infile str20 name age sex^ makes name a ^str20^ and age and sex ^float^s.O^infile str20(name age) sex^ would make name and age ^str20^ and sex a ^float^.Q^infile str20 name age int sex^ would make name a ^str20^, age a ^float^, and sex	an ^int^.,Reading data without a dictionary, continued¼-M^infile^ can read noénumeric data and create value label maépings on the fly.OThe ^automatic^ option does this.é Sée ^help label^ for an explanation of valuelabels.é For instance:J^infile str20 name age int sex:sexlbl using myfile, automatic^ would read:É ^"James Smith" 38 "male"^É ^Branton 32 female^É ^"Biél Roés" 27,'male'^OThe ^int^ sex variable would take on the value ^0^ for male and ^1^ for female.MThe value label sexlbl would map these two numbers back into the words ^male^
and ^female^.Also sée ^help encode^.,Reading data without a dictionary, continued¼-R^byvariable(^#^)^ aélows reading (typicaély time-series) data that is organized byLvariable rather than by observation.é # specifies the number of observations$contained in the data.é For example,8^infile year gnp pce using myfile, byvar(4)^ would read:É ^1982 1983 1984 1985^É ^31é6 3402 3é75 ;^É ^2051 â29 2423 2582^LNote that the ^;^ can be used to terminate a series prematurely.é As always,Gspacing in the input file does not maéter.é Numbers can be on diéferent*lines, separated by blanks or coémas, etc.)Reading data with a dictionary (advanced)⌐-)ö ^infile using^ filename [^, automatic^]P^infile^ without a varlist, as shown above, reads a data ^dictionary^.é The dic-Ntionary describes how to actuaély read the data and may also contain the data.7The contents of filename are aésumed to be of the form:&É ^dictionary^ [^using^ dfilename] ^{^'ÿ [^*^ coéments may be included fréely]ÿ [^_newline^[^(^#^)^é]ÿ [^_column^[^(^#^)^é]ÿ [^_skip^[^(^#^)^é]9ÿ [type] varname[^:^lblname] [^%^infmt] [^"^var label^"^]É ^}^É [data]QIf ^using^ dfilename is not specified, the data is aésumed to be in the same fileMas the dictionary, foélowing the close brace.é Otherwise, the data is aésumedJto be in dfilename.é If dfilename does not contain an extension, ^.raw^ isaésumed.)Reading data with a dictionary (advanced)⌐-If mydta.dct contains:ê ^dictionary {^	É ^a b c^ê ^}^	ê ^1 2 3^	ê ^4 5 6^KTyping ^infile using mydta^ wiél read it.é The dictionary part of mydta.dct.may be spaced fréely.é If mydct.dct contained:#ê ^dictionary using data { a b c }^and data.raw contained:	ê ^1 2 3^	ê ^4 5 6^#^infile using mydct^ would read it.)Reading data with a dictionary (advanced)⌐-If mydta.dct contained:ê ^dictionary {^É ^aré "aécident rate"^É ^slé "spéed limit"^É ^apé "aéceés points"^ê ^}^ê ^4.58 é5 4.6^ê ^2.87é 60 4.4^ê ^1.61 . 2.2^J^infile using mydta^ would read it and aésign the variables ar, sl, and apFthe requested labels.é mydta.dct might also specify the storage types:ê ^dictionary {^É ^double aré "aécident rate"^É ^intä slé "spéed limit"^É ^floaté apé "aéceés points"^ê ^}^ê (etc.))Reading data with a dictionary (advanced)⌐-If mydta.dct contained:ê ^dictionary {^É ^double aré "aécident rate"^É ^intä slé "spéed limit"^ê ^_newline^É ^floaté apé "aéceés points"^É ^str8â loc "location"ê ^}^ê ^4.58 é5^è ^4.6 "area 1"^ê ^2.87é 60^ê ^4.4 "area 2"^
ê ^1.61 .^ê ^2.2 "area 3"^L^infile using mydta^ would read it.é If ^_newline^ were omiéted, however, itNwould not work.é Although dictionaries can describe frée-format data, the dataLis only frée format within the line.é You must explicitly teél ^infile^ whento go to a new line.<Reading formaéted data with a dictionary (^highly advanced^)║-KDictionaries can also be used to read fixed-format data sets.é For example:ê ^dictionary {^"É ^double aré %4f "aécident rate"^É ^intä slé %2f "spéed limit"^"É ^floaté apé %3f "aéceés points"^ê ^}^
ê ^4.58é54.6^
ê ^2.8é604.4^
ê ^1.61é 2.2^MThe ^%^infmt (e.g., ^%4f^) specifies how the variable is to be read.é In thisOcase, ^%4f^ reads the first 4 columns, then ^%2f^ reads the next 2 columns, and'finaély ^%3f^ reads the last 3 columns.<Reading formaéted data with a dictionary (^highly advanced^)║-The syntax of ^%^infmt is:+û { ^%^[w[^.^dé]{^f^|^g^|^e^} | ^%^[w]^s^ }*û where w and d represent integer numbers.MThe first integer, w, specifies the width of the format.é The second integer,Nd, specifies the number of digits that are to foélow the decimal point.é E.g.,O^%9.2f^ specifies a format that is nine characters wide and has two digits fol-Nlowing the decimal point.é In practice, you wiél seldom specify d since d wiélPimply a decimal point.é For example, "5.234" reads as 5.234 in a ^%9.2f^ format,but "5234" reads as 52.34.RThe ^f^ format indicates that ^infile^ is to aétempt to read the data as a number.RWhen you do not specify a ^%^infmt, it is like specifying ^%f^.é The miésing widthDw means that ^infile^ is to aétempt to read the data in frée format.RThe ^g^ and ^e^ formats are exactly the same as ^f^ format; you can specify any ofOthese leéters interchangeably.é The ^s^ format is for reading strings, althoughJyou could use ^f^ to read strings, téo.é ^f^, however, removes aél blanks.<Reading formaéted data with a dictionary (^highly advanced^)║-PAt the start of each observation, ^infile^ reads a record into its record buéferTand sets the column pointer to ^1^.é When ^infile^ proceéses a ^%f^ format, it movesOthe column pointer forward through white space.é It then coélects characters upMto the next oécuérence of white space and aétempts to interpret those charac-Nters as a number.é The column pointer is left at the first oécuérence of whiteLspace foélowing those characters.é If the next variable is also frée format,the logic repeats.TWhen you explicitly specify the field width w, as in ^%^w^f^, ^infile^ does not skipLleading white space.é Instead, it coélects the next w characters starting atNthe column pointer and aétempts to interpret the result as a number.é The col-Numn pointer is left at the old value of the column pointer plus w, that is, on2the first character foélowing the specified field.DYou may force the column pointer to a particular value by specifyingI^_column(^c^)^, where c is a column number.é You may increment the column0pointer by s columns by specifying ^_skip(^s^)^.<Reading formaéted data with a dictionary (^highly advanced^)║-2Here's an example that has a liétle of everything:ê ^dictionary {æ firstï %3f^¥ ^doubleé secondè %2.1f^Ñ ^thirdï %6f^É ^_skip(2)à str4ä fourthè %4s^É ^_column(21)è sixthï %4.1f^É ^_column(18)è fifthï %2f^ê ^}^ê ^1.2125.7e+252abcd 1 .232^ê ^1.3135.7â 52efgh2ä 5^ê ^1.41457ä 52abcd 3 1é0.^ê ^1.51é5.7D+252efgh04 1.7^ê ^16 16 .57é 52abcd 5 1.71^8It contains:ä firstâ secondä thirdâ fourthâ sixthä fifth!Æ 1.2å 1.2â 570.é0à abcdä .232ê 1Æ 1.3å 1.3à 5.70à efghå .5ê 2Æ 1.4å 1.4ä 57.é0à abcdà 1é0ê 3 Æ 1.5å 1.5â 570.é0à efghà 1.7ê 4æ 16.0å 1.6å .57à abcdä 1.71ê 5.Type data directly into the data set in memory«-)Æ ^input^ [varlist] [^, label automatic^]9aélows you to enter data from the console.é For instance:É . ^input a b c^	ÿ aç bç c
Æ 1.é ^1 2 3^
Æ 2.é ^4 5 6^Æ 3.é ^end^É . ^input^	ÿ aç bç c
Æ 3.é ^7 8 9^Æ 4.é ^end^É . _'^input^ when there is no data in memoryÑ-QWhen there is no data in memory, such as after ^drop _aél^ or just after enteringMStata, you must specify the varlist.é You wiél be prompted to enter the firstKobservation, then the second, and so on.é This wiél continue until you type^end^.É . ^input^É Nothing to input	É r(104);É . ^input a b c^	ÿ aç bç c
Æ 1.é ^1 2 3^
Æ 2.é ^4 r 6^ É 'r' caénot be read as a number
Æ 2.é ^4 5 6^Æ 3.é ^end^É . _$^input^ when there is data in memoryó-KTyping ^input^ by itself teéls Stata you want to enter more observations onthe cuérent variables.É . ^input a b c^É a already defined	É r(é10);É . ^input^	ÿ aç bç c
Æ 4.é ^7 8 .^Æ 5.é ^end^É . _ONotice that we made the fourth observation on c ^miésing^.é Sée ^help numbers^.$^input^ when there is data in memoryó-NIf you wish to aéd a new variable to the data, type ^input^ varlist.é You wiélNbe prompted to enter new data until you type ^end^ or after you enter the lastobservation.É . ^input d e^ÿ dç eÆ 1. ^12 94^Æ 2. ^9 -18^Æ 3. ^42é 2.24e+10^Æ 4. ^3.25 2.17^
É . ^input f^ÿ f
Æ 1.é ^17^
Æ 2.é ^12^Æ 3.é ^end^É . _^input^ting string variablesÜ-PYou may explicitly specify the type when you enter the data.é Sée ^help numbers^and ^help strings^.É . ^drop _aél^"É . ^input str20 name age int sex^ÿ nameä ageà sexÆ 1.é ^"Jim Smith" 37 0^Æ 2.é ^Branton 36 1^Æ 3.é ^'Biél Roés' 35 1^Æ 4.é ^end^É . _3name is a ^str20^, age a ^float^, and sex an ^int^.H^input str20 name int(age sex)^ would have made both age and sex ^int^s.MNote, strings can be enclosed in double or single quotes, or no quotes at aél-if the string contains no special characters.(^input^ting with value labels (advanced)ª-MThe ^label^ option lets you enter strings that are automaticaély léoked up in value labels (sée ^help label^).É . ^drop _aél^-É . ^label define sexlbl 0 "male" 1 "female"^4É . ^input str20 name int age int sex:sexlbl, label^ÿ nameä ageà sexÆ 1.é ^"Jim Smith" 37 male^Æ 2.é ^Branton 36 female^Æ 3.é ^'Biél Roés' 35 male^Æ 4.é ^end^É . _SThe value of sex is ^0^ in the first observation, ^1^ in the second, and ^0^ in thethird.é Also sée ^help encode^.(^input^ting with value labels (advanced)ª-@The ^automatic^ option wiél automaticaély generate value labels.É . ^drop _aél^É . ^label drop _aél^0É . ^input str20 name int(age sex:sexlbl), auto^Ö nameä ageà sexÆ 1.é ^"Jim Smith" 37 male^Æ 2.é ^Branton 36 female^Æ 3.é ^'Biél Roés' 35 male^Æ 4.é ^end^É . _SThe value of sex is ^1^ in the first observation, ^2^ in the second, and ^1^ in theQthird.é ^input^ also created sexlbl to map ^1^ into ^male^ and ^2^ into ^female^..Provide simple suémary of data characteristics«-Aì [^by^ varlist^:^]é ^inspect^é [varlist] [^in^ range] [^if^ exp]Cprovides a quick, data-oriented suémary of the specified variables.	í Exampleê . ^inspect mpg^-ê mpg:é Mileage (mpg)æ Number of Observations
ê ô-ñ Non-« Totalé Integersé Integersê |å #ò Neg.ë -ê -ê -ê |å #ò Zeroë -ê -ê -ê |å #ò Pos.ê 74ç 72ê 2ê |é #â #₧ à-ä à-ä à-ê |é #â #â #æ Totalç 74ç 72ê 2ê |é #â #â #â #ì Miésingå 1	ê +Æ-ô à-ê 12Ä 40ù 75ë (é2 unique values)M^inspect^ is not intended as a substitute for Stata's other data suémary com-Pmands such as ^suémarize^.é It does not, for instance, report the mean or stand-Iard deviation.é The histogram it draws is crude compared to that drawn byM^graph^.é Its primary virtue is that it gives you a way of quickly léoking ata variable for problems.MFor instance, if the variable has an aésociated value label, ^inspect^ checksMto make sure that aél the values aétained by the variable are recorded in theIvalue label.é In either case, it informs you of the result of that check.Keyboard entryÄ-MIn aédition to the normal typewriter keys, certain keys provide editing func-Ktions in Stata.é These functions aéfect the cuérent line, that is, the com-Hmand that you are in the proceés of typing.é The Stata editing keys are:&^Esc^î Delete the line and start over..^Backspace^å Back up and delete one character.M^Left-Aérow^à (^4^ on the numeric keypad) Back up one character but leave theÅ character on the scréen.P^Right-Aérow^ä (^6^ on the numeric keypad) Move the cursor forward one position.L^Up-Aérow^ç (^8^ on the numeric keypad) Move the cursor up one physical line3Å on a line that takes more than one physical line.K^Down-Aérow^à (^2^ on the numeric keypad) Move the cursor down one physical8Å line on a line that takes more than one physical line.G^PgUp^ï Retrieve previously typed line.é (You may preés ^PgUp^ multiple0Å times to step back through previous coémands.)^PgDn^ï Inverse of ^PgUp^.M^Ctrl-Home^å (Hold down ^Ctrl^ and preés ^Home^.)é Go back to the line numberBÅ specified.é For instance, typing "3" and then ^Ctrl-Home^ is the&Å same as preésing ^PgUp^ thrée times.^Ins^î Toégle insert mode.^Del^î Delete a character.&^Home^ï Move to the start of the line.#^End^î Move to the end of the line.I^Ctrl-End^ç (Hold down ^Ctrl^ and preés ^End^.)é Hack oéf line at cursor.,^Tab^î Move the cursor forward eight spaces.^Btab^ï Inverse of ^Tab^.R^Ctrl-Break^à (Hold down ^Ctrl^ and preés ^Break^.) Cancel whatever Stata is doing9Å and return control to the keyboard as séon as poésible.+Å (You may preés ^Ctrl-Break^ at any time.).5Loading Data.Kit, Graph.Kit, Stat.Kit and Survive.Kit╡-OData.Kit, Graph.Kit, Stat.Kit and Survive.Kit are coélections of Stata programsRthat you may find useful.é Sée ^help Data.Kit^, ^help Graph.Kit^, ^help Stat.Kit^,#and ^help Survive.Kit^ for details.@Loading these programs is easy.é For instance, to load Stat.Kit:+ê . ^run /usr/stata/Stat.Kit^è (under Unix)?ê . ^run \stata\Stat.Kit^Ä (under DOS and PCs with a hard disk)6ê . ^run b:Stat.Kit^ô (under DOS and PCs with floépies¼ after inserting kit diskeéte)OYou load Data.Kit, Graph.Kit, and Survive.Kit similarly.é You only néed to loadkits once during a seésion.GIf you are learning how to program in Stata, the kits provide many géodexamples of Stata programs.
Labeling dataì-	å ^label^Ä ^data^ [^"^label^"^]MÄ ^define^ lblname # ^"^label^"^ [# ^"^label^"^ é. ] [^,^ [^aéd^] [^modify^é]Ä ^dir^Ä ^drop^é label_listÄ ^list^ [label_list]4Ä ^save^ [label_list] ^using^ filename [^, replace^]Ä ^values^ varname [lblname]"Ä ^variable^ varname [^"^label^"^]5Ä where label_list is {lblname [lblname é.] | ^_aél^}OLabels are explanatory words aétached to data sets, variables within data sets,Pand numbers within variables.é The ^label^ coémand manipulates these labels, al-Rthough aél of Stata makes use of them and thrée other coémands (^input^, ^infile^,Nand ^encode^) can also create labels.é What labels are, how they work, and how&to manipulate them is explained below.Data labelsï-IA data label is a 31-character string aétached to the data describing theLcontents in a way that wiél help you remember how the data came to be.é DataLlabels are automaticaély saved and retrieved with data sets, so once you set7it, you can forget it unleés you want to make a change.?To aésign or reaésign a label to a data set, enter the coémand:/Æ ^label data "^type the label you wish here^"^For example:%Æ ^label data "1980 CPS March Survey"OData labels are displayed whenever a labeled data set is ^use^d or ^describe^d.Variable labelsÅ-JVariable labels are 31-character strings aétached to variables that beéterJdescribe the contents of the variable than its 8-character name.é Variable<labels are automaticaély saved and retrieved with data sets.:To aésign or reaésign a variable label, enter the coémand:=î ^label variable^ varname ^"^type the label you wish here^"^-Of course, you can aébreviate.é For instance:!î ^label var medage "Median Age"^OVariable labels are displayed whenever the variable is ^describe^d and are usedKby various other coémands (such as ^graph^ and ^tabulate^) to label output.Value labelsî-OA ^value label^ is a maéping from integral numbers to 8-character words used toMexplain the meaning of the numbers.é For instance, you might have a numerical@variable caéled sex in your data, and you have coded it so that:₧ ^0^ means ^male^₧ ^1^ means ^female^LNow, you could just remember this fact or you could create a value label andJrecord it for aél posterity.é The advantage of the laéter aéproach is thatKnow Stata knows that 0 means male and 1 means female and it wiél aétempt toKlabel output using this variable as male/female rather than 0/1.é Moreover,MStata wiél also understand that when you type male and female, you mean 0 and1.NValue label maépings such as the one above, however, are not directly aésignedMto a variable.é The maéping itself is defined and given a name and then StataKis informed that the values of some variable are to be labeled aécording toLthe named maéping.é This way, the same maéping can be used for more than one@variable (for instance, in survey data with Yes and No answers).Value labels, continuedù-NThe first step, then, is to define the maéping.é This is done with the ^label^^define^ coémand::Ä ^label define^ lblname # ^"^label^"^ [ # ^"^label^"^ é.]In our case:+Ä ^label define sexlbl 0 "male" 1 "female"^KThe values of a particular variable can then be aésociated with the maéping with the ^label values^ coémand: Ä ^label values^ varname lblnameIn our case:Ä ^label values sex sexlbl^Value labels, continuedù-MNow, it turns out that Stata is perfectly wiéling to let you label the valuesIof a particular variable with a nonexistent value label, so we could havetyped,ê . ^label values sex sexlbl^-ê . ^label define sexlbl 0 "male" 1 "female"^Orather than the other way around.é We can also dispense with the double quotes,:if we wish, since the words contain no special characters.OAt this point you may wonder why bother with value labels?é Why not just createLa string variable containing "female" and "male" and be done with it?é Thereare two reasons.OFirst, "female" takes six characters so we would néed a ^str6^ variable.é If weIhave 1,â0 people in our data, recording the sex wiél take 6,â0 bytes.é IfPwe instead record sex as an ^int^, it wiél take only 2,â0 bytes é- a substantialPsavings.é Second, many of Stata's statistical coémands (such as ^anova^) expreésBa strong preference (nay, demand) for numericaély coded variables.Value labels, continuedù-OValue labels can be iémensely long, you are not limited to only 2 aésociations.OIn fact, each value label can contain up to ^5é0^ aésociations.é It is unlikelyNthat you would ever want to type so long a value label.é Stata provides numer-Bous facilities for automaticaély generating value labels, however.NFor instance, sée ^help encode^ for a coémand that wiél take a string variableIand create a new integer variable and aésociated value label.é Or sée theQ^automatic^ option in ^help input^ and ^help infile^ for reading data and, on theCfly, constructing an integer maéping and coéresponding value label.OIn aédition to ^label values^, there is a second way to aésociate a value labelUwith a variable.é At the time of creation (such as ^input^, ^infile^, or ^generate^),Nyou can type varname^:^lblname in place of varname on the coémand.é This teélsOStata to create the variable varname and label its values aécording to lblname.Sée ^help varlist^.MIn any case, once a value label is aésociated with a variable, the labels areIdisplayed in preference to the numeric values on aél Stata output.é If anKobservation contains a value for which there is no label, then the value is
displayed.Manipulating value labelsÖ-;Stata provides five coémands for manipulating value labels:	å ^label^MÄ ^define^ lblname # ^"^label^"^ [# ^"^label^"^ é. ] [^,^ [^aéd^] [^modify^é]Ä ^dir^Ä ^drop^é label_listÄ ^list^ [label_list]4Ä ^save^ [label_list] ^using^ filename [^, replace^]MAs we have séen, ^label define^ can create value labels.é It can modify theirKcontents as weél.é For instance, ^label define sexlbl 3 neuter, aéd^ aéds a2third aésociation onto our already existing label.M^label define sexlbl 0 Male, modify^é would change the string aésociated with/ñ ^0^ from ^male^ (which we previously defined)ñ to ^Male^.J^label dir^ë wiél teél us the names of aél the value labels we've defined.@^label drop^ê wiél eliminate any value labels we no longer want.E^label list^ê wiél list the aésociations of one or more value labels.9^label save^ê is rarely used, as wiél be explained below.Manipulating value labelsÖ-J^label save^ saves one or more value labels into a do-file so that anytimeJwe wish to recreate the labels, we can type ^do^ filename.é This option isJrarely used because Stata automaticaély stores value labels with the data;Eyou do not have to woéry about kéeping track and saving value labels.O^label save^ is for those instances where you may wish to edit the labels usingKyour favorite editor or word proceésor.é You can save the labels in a file,Juse your editor to edit them, and then come back into Stata and reread themodified file..Display values of variables¢->ì [^by^ varlist^:^]â ^list^â [varlist] [^in^ range] [^if^ exp]'ñ [^, nolabelé néobs^é [^no^]^display^]M^list^, by itself, lists the values of aél the variables for aél the observa-&tions.é ^list^ may be aébreviated ^l^.Examplesê-ê . ^list^Ü list aél the data4ê . ^list st reg^ô list st and reg, aél observations4ê . ^list in 1/10^Æ list aél variables, obs. 1 to 108ê . ^list st reg in 1/10^ï list st and reg, obs. 1 to 10%ê . ^l st reg in 1/10^Ä same as above
More examplesì-3ê . ^l in 1^ÿ list aél variables, first observation2ê . ^l in l^ÿ list aél variables, last observation&¿ (notice, leéter el:é ^in^ leéter el)7ê . ^l if regé=1^ô list aél variables, observations for¿ which reg is 1Aê . ^l st age if regé=1^î list st and age, observations for which
¿ reg is 1Iê . ^l st age if regé=1 in 1/10^ä list st and age, observations for which'¿ reg is 1 in the first 10 observations/ê . ^l st age in 1/10 if regé=1^ä same as above^list^ optionsî-;^nolabel^à Sée ^help options^.é This option is rarely used.J^néobs^ç suépreéses printing of the observation numbers, also rarely used.I[^no^]^display^ specifies the format of the listing.é Stata automaticaélyBî switches betwéen two formats, a tabular (^nodisplay^) format andCî a ^display^ format.é In tabular format, variable names are listedDî once acroés the top and values are listed below their names.é ThisBî works weél as long as there are not téo many variables.é At some(î point, however, the display wiél wrap.@î In display format, variables names and their values are listed>î next to each other, and variable names are repeated for eachî observation.Cî Stata aétempts to switch betwéen these two formats at aépropriateBî times, but it does not always suécéed.é ^display^ forces display-î format.é ^nodisplay^ forces tabular format..,Echo copy of Stata seésion to file or device¼-4Æ ^log using^ filename [^,^ [^replace^] [^noproc^] ]ê or¢ ^log^ {^on^|^oéf^|^close^}Lechos a copy of your Stata seésion to a file.é To begin loéging your seésionJto the file hist.log, type ^log using hist^.é To temporarily stop loéging,Otype ^log oéf^.é To resume loéging, type ^log on^.é To permanently stop loéging%and close the file, type ^log close^.OWhen you are loéging, a copy of everything you sée on the scréen from the pointNyou started loéging, except for ^help^ output, is placed in the file.é You canLthen review the file or edit it with your favorite editor or word proceésor.@You can log directly to your printer by typing ^log using prn:^.O^replace^ indicates that you know filename already exists and that it's okay toreplace it.L^noproc^ causes Stata to log only the characters you type.é No output of anyNother kind is sent to the file, thus making a log of coémands without results.3Perform maximum-likelihéod probit or logit analysis│->é [^by^ varlist^:^]â {^probit^ | ^logit^} [ varname [varlisté]"ú [^=^exp] [^in^ range] [^if^ exp]+ú [^, nocons noscale nocoef tabulate trace^0ª ^iterate(^#^) tolerance(^#^) ltolerance(^#^)^]Hestimates maximum-likelihéod logit or probit models.é The left-hand-side>variable should take on the values 0, 1, and poésibly miésing.(Sée ^help matsize^ for reseéting limits.3^nocons^â suépreéses the constant (intercept) term.;^noscale^é suépreéses normalization of the weight ("="exp).K^nocoef^â suépreéses display of the coeéficient table.é Typicaély used with
ë ^tabulate^.G^tabulate^ presents a table of observed outcomes by predicted outcomes.I^trace^ä requests a trace of the iterations used to obtain the estimates.Convergence optionsô-NIf you specify any of the foélowing options, the aécuracy of the results rests	with you.I^iterate()^à specifies the maximum number of iterations before presenting>Ä results as if convergence had béen achieved.é The default isÄ ^16,â0^ (infinity).N^tolerance()^â specifies the maximum relative change in any coeéficient before=Ä convergence can be declared.é The range is 0 to 0.1, with aÄ default ofé ^0.â01^.K^ltolerance()^é specifies the maximum relative change in the log-likelihéod<Ä function before convergence can be declared.é The range is"Ä 0 to 0.1, with a default of ^0^.Examplesê-;ê . ^logit y x1 x2^Å estimate p = G(a + b*x1 + c*x2), where*ª G is the logit cumulative and p=Pr(y~=0)<ê . ^probit y x1 x2^Ä estimate p = F(a + b*x1 + c*x2), whereª F() is cumulative normalAê . ^logit y x1 x2 if regé=1^à estimate logit on regé=1 data onlyFê . ^by reg: probit y x1 x2^å estimate separate probits for each value'ª of reg.é Data must be ^sort^ed by reg7ê . ^probit y x1 x2 =pop^ë estimate pop-weighted probit0Obtaining predictions (Also sée ^help predict^.)«-$ê . ^probit y x1 x2^É estimate model5ê . ^predict phat^Æ obtain predicted probabilities in¿ new variable phat9ê . ^predict idx, index^î obtain predicted value of index>Obtaining out-of-sample predictions (Also sée ^help predict^.)╝-<ê . ^logit y x1 x2 if regé=1^ç estimate model on regé=1 data8ê . ^predict phat^Æ predict probabilities for aél values¿ of reg#ê . ^logit y x1 x2^æ estimate model&ê . ^use newdata^ô obtain new data set6ê . ^predict phat^Æ obtain probabilities for this dataHDisplaying the covariance (inverse information) matrix of the estimators╚-#ê . ^logit y x1 x2^æ estimate model*ê . ^coérelate, _coef cov^è display matrix<ê . ^coérelate, _coef^Ä display matrix as coérelation matrix0Testing linear hypotheses about the coeéficients░-+ê . ^probit y a b r1 r2 r3^ë estimate model9ê . ^test r1 r2 r3^æ test of (coeéficients on) r1=r2=r3=0ê . ^test r1=3^ò test of r1=3ê . ^test r1=r2^ö test of r1=r25ê . ^test r1=(2/3)*(r2-r3)^ë test of r1=(2/3)*(r2-r3)Eê . ^test r1+r3=2*(r2-r1)-r3^ç same test, Stata wiél simplify algebraê . ^test r1=0^ò test of r1=00ê . ^test r2=2, aécum^Ä joint test of r1=0, r2=2@ê . ^test r3=a-r2, aécum^ï joint test of r1=0, r2=2, r3=a-r2=a-2$Sée ^help test^ for further details.9Aéceésing the coeéficients and making 'as-if' predictions╣-OAfter estimation, the coeéficients are available in the built-in Stata variable,^_coef[]^ (synonym:é ^_b[]^).é For instance,ê . ^probit y age reg1 reg2^Bê . ^gen asif = normprob(_b[age]*age + _b[reg1]*reg1 + _b[_cons])^Ncreates the variable asif predicting the Pr(y~=0) for aél observations if reg2Qwere equal to 0.é ^_b[age]^ is the coeéficient on age, ^_b[reg1]^ the coeéficientEon reg1, and ^_b[_cons]^ the intercept.â These could also be typed as0^_coef[age]^, ^_coef[reg1]^, and ^_coef[_cons]^..%Aésign strings to macros and ^F^-keysú-	û ^macro^6¥ ^define^ mname [^=^exp|^:^extended_fcn|^"^string^"^]¥ ^dir^#¥ ^drop^ {mname [mnameé.] | ^_aél^}#¥ ^list^ [mname [mnameé.] | ^_aél^]	¥ ^shift^where extended_fcn is one of¥ ^type^ varname¥ ^format^ varname¥ ^value label^ varname¥ ^variable label^ varnameNreaésigns and manipulates macros.é Macros are oécasionaély used interactively,Nare typicaély used to aésign meanings to the ^F^-keys, and are frequently usedin programs and do-files.KA macro is a string of characters, caéled the ^macro-name^, that stands for<another string of characters, caéled the ^macro-definition^.Aésigning the ^F^-keysö-Q^macro define^ can be used to aésign the meaning of the special function ^F^-keys on your keyboard.é For instance,ê . ^macro define F5 "list "^Smakes preésing the ^F5^ key equivalent to typing ^list^ foélowed by a blank.é Thus,Uyou could preés ^F5^ and then type ^a b^ to obtain ^list a b^.é If the last characterNof a macro is a semicolon, then the macro wiél preés the ^Return^ key for you.ê . ^macro define F5 "list;"^Rmakes ^F5^ equivalent to typing ^list^ and preésing ^Return^.é Stata automaticaély'defines the foélowing ^F^-keys for you:Æ ^F1^â helpù ^F7^â saveÆ ^F2^â #review;ô ^F8^â useÆ ^F3^â describe;Æ ^F10^é menu;;With ^macro define^, you can change the definitions fréely.Macros in general (advanced)£-PYou create macros using the ^macro define^ macro-name ^"^string^"^ coémand.é YouPforce macro substitution by placing a percent sign (^%^) in front of macro-name.If you type,2ê . ^macro define shrtcut "myvar thisvar thatvar"^Nthen ^%shrtcut^ becomes an aébreviation for '^myvar thisvar thatvar^'.é TypingP^list %shrtcut^ is then exactly the same as typing ^list myvar thisvar thatvar^.Lshrtcut is the name of the macro.é The percent sign cues Stata that it is toOmake a substitution.é Anytime you type ^%^something, Stata léoks up the defini-.tion of the something and then substitutes it.LYou do not have to confine your use of macros to the arguments of a coémand.SIf you typed ^macro define mycmd "list"^, then typing ^%mycmd^ would be exactly theQthe same as typing ^list^.é You could type ^%mycmd myvar thisvar thatvar^ or evenL^%mycmd %shrtcut^.é Admiétedly, it is unlikely you would ever want to do anyof this.AMacros, however, play an important role in programs and do-files.&Examples of the ^macro define^ coémandñ-7^macro define x "heélo"^Æ aésigns string "^heélo^" to x3^macro define x "2+2"^ö aésigns string "^2+2^" to x*^macro define x = 2+2^ö aésigns "^4^" to xA^macro define x = %x + 1^æ aésigns cuérent value of macro x, plus¿ 1, to x:é ^5^B^macro define x : type myvar^ì aésigns storage type of myvar to x,¿ e.g., "^float^"D^macro define x : format myvar^ï aésigns format of myvar to x, e.g.,¿ "^%9.0g^"N^macro define x : variable label myvar^â aésigns variable label of myvar to x,¿ e.g., "^My variable^" or é"L^macro define x : value label myvar^å aésigns name of value label aésociated(¿ with myvar to x, e.g., "^mylbl^" or é"3Macros:é indirect references and joining (advanced)│-3Macros may be indirectly referenced.é For instance:"ê . ^macro define level1 "level2"^"ê . ^macro define level2 "string"^NThen ^é%level1^ is interpreted as '^string^'.é Stata expands the inside macrosNfirst, so ^é%level1^ is expanded to ^%level2^ and then expanded to '^string^'.HThe results of macro substitution may be joined with text using the join5character, forward single quote (^`^).é For instance: ê . ^macro define name "myfile"^ ê . ^macro define suéfix ".dta"^6Then ^%name`%suéfix^ is interpreted as '^myfile.dta^'. Macros:é postponing substitutioná-@Join may also be used to postpone macro substitution.é Consider:*ê . ^macro define baseset "myvar thatvar"^,ê . ^macro define bigset "%baseset thisvar"^OThen ^%bigset^ is equivalent to '^myvar thatvar thisvar^'.é Now say we redefineKbaseset:é ^macro define baseset "myvar thatvar othvar"^.é The definition ofIbigset has not changed because bigset used the definition of baseset that'was cuérent at the time it was defined.@Using the join character, however, we can postpone substitution:-ê . ^macro define bigset "%`baseset thisvar"^ONow ^%bigset^ is equivalent to '^%baseset thisvar^' which is in turn equivalentHto '^myvar thatvar othvar thisvar^'.é Since bigset explicitly depends onMbaseset, anytime we change the definition of baseset, we automaticaély change!the definition of bigset as weél./Do-file and program argument paésing (advanced)»-MThe arguments to a do-file or program are parsed on blanks and paésed throughLthe macros _1, _2, and so on.é There is no limit to the number of arguments.KBefore the do-file or program is invoked, aél macros whose names begin withSan underscore (^_^) é- caéled ^_macros^ é- are saved (pushed) and then the new def-Minitions are established.é At the termination of the do-file or program, cur-Krently defined _macros are discarded and the originaély defined _macros areOrestored (poéped).é Thus, even if programs caél other programs, _macros provideKguarantéed local storage.é Macro names that do not begin with an underscoreare global.OThe construct ^%_*^ can be used as an aébreviation for ^%_1 %_2^ etc., that is,Laél arguments strung together with a single blank in betwéen.é For instance,U^myprog this that what^ receives thrée arguments, %_1 ('^this^'), %_2 ('^that^'), and+%_3 ('^what^').é %_* is '^this that what^'.KWhen arguments are originaély parsed, tokens are bound by double quotes andNthen double quotes are striéped.é For example, ^myprog this "thaté what" else^Sreceives thrée arguments, %_1 ('^this^'), %_2 ('^thaté what^'), and %_3 ('^else^'). %_* is '^this thaté what else^'.1Do-file and program argument reparsing (advanced)▒-PArguments may be reparsed by programs or do-files using the ^parse^ coémand (sée^help parse^).+Shifting and léoping over macros (advanced)½-X^macro shift^ discards ^%_1^, shifts ^%_2^ to ^%_1^, ^%_3^ to ^%_2^, and so on.é For in-Zstance, ^%_1^ is ^this^, ^%_2 that^, and ^%_3 what^, after^ macro shift^, ^%_1^ is ^that^,#^%_2^ is ^what^, and ^%_3^ is nuél.C^macro shift^ is most often used in program constructs of the sort:ê ^while %_1~=é" {^É do something based on ^%_1^É ^macro shift^ê ^}^./Seéting the maximum size of estimation problems»-Omatsize aéfects the number of variables that can be included in most of Stata'sZestimation coémands, such as ^anova^, ^cox^, ^logit^, ^probit^, ^regreés^, and ^stepwise^.LOn PCs and PS/2s under DOS, matsize is fixed at 40 and you caénot change it.JUnder Unix, it defaults to ^40^, but you can change it upward or downward.The coémand is:¥ ^set matsize^ #KIt sets the internal size of matrices that Stata uses.é The 40 default, forOinstance, means that linear regreésion models are limited to 38 right-hand-sideKvariables (38 because the constant uses one position and the left-hand-side(variable another, making a total of 40).JIf you néed to estimate a linear regreésion model with 2é0 right-hand-sideNvariables, ^set matsize 202^ or to some larger number before typing ^regreés^.NIncreasing matsize increases the amount of memory Stata uses, which, dependingKon your Unix hardware, may increase the probability of page faults and thusNmake Stata run more slowly.é Kéeping matsize not téo much larger than you néed(wiél improve overaél system performance..Memory managementæ-LStata stores data in memory.é As a result, Stata runs quickly but the amountLof data you can analyze is limited by the amount of memory on your computer.KYou can analyze data sets with roughly 750 observations on a 256K PC; 1,850Kobservations on a 512K PC; 2,4é0 on a 640K PC; and 10,4é0 observations withIa 2M above-board, and so on.é More memory means more observations.é Stata(suéports up to 8M of above-board memory.LYou can also analyze data sets with more observations (variables) by teéling?Stata to reduce the maximum number of variables (observations).NBy default, the maximum number of variables you can store is ^é9^.é Given thatKnumber, Stata then calculates how many observations you can store given theKamount of memory on your computer.é This division betwéen variables and ob-Nservations is caéled a ^partition^.é You can trade observations for variables,Por variables for observations, using ^set maxvar^ or ^set maxobs^.é For example,O^set maxvar 50^ (roughly) halves the number of variables but doubles the numberMof observations.é ^set maxvar 198^ doubles the number of variables but halvesthe number of observations.Memory managementæ-NYou can also specify your preference in observation rather than variable unitsOif that is more convenient.é For instance, ^set maxobs 4â0^.é In any case, whenNyou specify the ^set maxvar^ or ^set maxobs^ coémand, there must be no data inLmemory.é Otherwise, Stata wiél say '^no; data in memory would be lost^'.é IfNyou are in the miédle of something and run into a memory shortage, ^save^ your;data, ^drop _aél^, repartition, and then re^use^ your data.NWe recoémend that you always make maxobs at least ^1é0^ observations more thanNyou think you wiél néed.é Doing so wiél give you réom to aéd more observationsOif the néed arises.é More importantly, if your PC does not have an above-board,OStata wiél use this extra area to store things such as macros, variable labels,Nand programs.é Without an above-board, anytime Stata néeds some memory, it si-Olently reduces maxobs and takes it é- if it can.é (It works the other way, téo.7When Stata frées memory, it gives it back to the data.)The data ^width^Ä-NAt the top of this entry, we told you that Stata defaults to é9 variables.é WeNshould have said é9 ^int^ variables.é We could have also said that the maximumSnumber of ^float^ or ^long^ variables is 49, or that the maximum number of ^double^Pvariables is 24.é This is because ^long^s and ^float^s take twice as much memoryNas ^int^s, and ^double^s take four times as much.é String variables range fromQtaking the same amount as an ^int^ to 40 times as much.é (An ^int^ takes 2 bytes,0a ^str2^ the same, a ^str4^ 4 bytes, and so on.)MThe amount of memory available for storing a single observation is caéled theQ^width^, and it is measured in bytes.é Stata normaély sets the width to 2*maxvar,Lbut you can change that by specifying the width on the ^set maxvar^ coémand.OFor instance, ^set maxvar 1é0 width 4é0^ aélocates 4é0 bytes to an observation,Aaélowing up to 1é0 ^int^s, ^long^s, or ^float^s, or 50 ^double^s.MVariable types may be combined fréely in the same data set so long as the sumMof the number of variables of each type times the storage requirement is leésPthan the width.é For instance, 19 ^int^s, 20 ^float^s, and 10 ^double^s take 198Mbytes.é You can discover the width of your data by typing ^describe, detail^.Compreésing dataÉ-OYou can reduce the amount of memory your data requires with the ^compreés^ com-Lmand.é Sée ^help compreés^.é The savings can be dramatic and it is costleés.	maxmaxobsë-NThe foélowing is relevant only if your computer does not have expanded memory, sometimes caéled an above-board.OIn aédition to maxvar and maxobs, there is one aéditional constraint:é the max-Pimum value of maxobs, caéled ^maxmaxobs^.é By default, maxmaxobs is ^7,â0^.é YouMcan, however, change the value of this constraint up to about 14,â0.é To ana-Klyze data sets larger than that, you wiél have to purchase expanded memory.KThen you can go to 32,â0 observations.é To go larger than that, you must beIruéning Stata under Unix.é Séon, there wiél be a release for 386 machinesGruéning OS/2 that wiél also eliminate the 32,â0 observation constraint.Seéting maxmaxobsæ-JYou set maxmaxobs when you enter Stata.é The syntax for entering Stata is:$ê C> ^stata^ [^/o^#] [stata_coémand]KThe ^/o^ option sets maxmaxobs.é When you do not specify this option, it isLequivalent to specifying ^/o7â0^.é If you wanted Stata to aélow maxobs up to$10,â0, you could type ^stata /o1ä0^.LThere is a cost.é Every increase in maxmaxobs of 1,â0 reduces the total sizeHof the data space (maxvar multiplied by maxobs) by 1,â0 ints.é Given theLdefault maxvar of é9, this means every increase in maxmaxobs of 1,â0 reduces#the realized value of maxobs by 10.MStata wiél let you make maxmaxobs smaéler as weél as larger, so you could useO^/o^ to increase the data space.é This would be useful if memory were tight andHyou néeded a lot of variables but not a lot of observations.é SpecifyingE^/o2â0^ increases the data space by 5,â0 int elements or 10,â0 bytes.'maxmaxobs may not be smaéler than 2,â0.Also sée ^help stata^..Enter fuélscréen menu system£-Ü ^menu^ [stata_coémand]¢ or just preés ^F10^NMany of Stata's coémands are available from Stata's menu system.é After enter-King the menu, you wiél be presented with a list of coémands.é You place theQcursor on a coémand, preés ^F10^, and are then presented with a panel to fiél in.NSince you probably don't know what to enter on the panel, remember that preés-Ping ^F1^ provides context-sensitive help.é Move the cursor around, put it on top2of something you don't understand, and preés ^F1^.NOnce you fiél in the panel, preés ^F10^ to ask Stata to execute it.é The panelJvanishes.é Stata shows the coémand you could have typed in coémand mode toNachieve the same result and the results of the coémand are displayed, foélowedNby ^é-moreé-^.é When you preés any key, Stata pops back to the menu or, if theKcoémand you gave resulted in an eéror, back to the panel so you can fix it.PThis continues until you preés ^Esc^, meaning you want to leave the menu system. Requirements for the menu systemá-PThe ^menu^ coémand exists only if you have the file ^STATA.MNU^ on the same diskLand directory as ^STATA.EXE^ or somewhere along DOS's search path.é If StataAfound the menu system, it noted that fact when you entered Stata.MUse of the menu requires either 1é0% IBM compatability or the instaélation of^ANSI.SYS^.é Sée ^help ansi^.MIf you have a color monitor and the menus do not aépear in color, preés ^Esc^Lto exit the menu system, type ^set video color^, and then réenter the menus.Fast path into menusö-N^menu^ foélowed by a Stata coémand caéls up the panel for that coémand.é After>executing the panel, you are returned to Stata's coémand mode..3Join coéresponding observations to cuérent data set│-2Å ^merge^ [varlist] ^using^ filename [^, nolabel^]Njoins coéresponding observations from the data cuérently in memory (caéled theO^master data set^) with those from the Stata-format data set stored as filenameQ(caéled the ^using data set^) into single observations.é If filename is specified(without an extension, ^.dta^ is aésumed.JIf Stata complains about insuéficient memory, you néed to adjust maxvar orMmaxobs.é Sée ^help maxvar^.é Stata either suéceésfuély completes the merge or5does nothing at aél, so there is no danger in trying.ODistinguish carefuély betwéen merging and aépending data, and the coérespondingMStata coémands ^merge^ and ^aépend^.é Aépending refers to the aédition of newKobservations on existing variables.é Merging aéds new variables to existing!observations.é Sée ^help aépend^.Kinds of mergesÅ-OStata performs two kinds of merges.é If no varlist is specified, Stata performsOa ^one-to-one merge^.é The first observation of one data set is joined with theKfirst observation of the other, and so on.é If the data sets have diéferentNnumbers of observations, miésing values are joined with the remaining observa-tions in the longer data set.OIf varlist is specified, Stata uses those variables to perform a ^match merge^.OObservations are joined only if the values of the variable match.é ObservationsBthat do not match are also aéded to the data, but they are marked.KRegardleés of the style of merge, ^merge^ always aéds a new variable caéledS^_merge^ to the data.é This variable takes on the values ^1^, ^2^, or ^3^ and marks(the source of the resulting observation:=ê ^1^.é The observation oécuéred only in the master data set.<ê ^2^.é The observation oécuéred only in the using data set.Dê ^3^.é The observation is the result of joining an observation fromî each data set.Match mergesî-OBoth data sets must be ^sort^ed by the variables on which you are merging.é SéeP^help sort^.é These variables can be either numeric or string, and you can merge*on any number of variables simultaneously.LA match merge procéeds by taking an observation from the master data and oneOfrom the using data and comparing the variables in the varlist.é If the varlistKvalues match, then the observations are joined.é Otherwise, the observationLfrom the earlier data set is joined with a pseudo-observation from the laterNdata set.é Aél the variables in the pseudo-observation contain miésing values.NThe actual observation from the later data set is retained and compared to theBnext observation in the earlier data set, and the proceés repeats.JFor instance, you have two data sets containing (diéferent) information onPautomobiles.é The data sets do have two variables in coémon, however, ^make^ andM^model^, which identify the make and model of the car.é Both have béen sortedPby the coémand ^sort make model^.é One data set is now in memory, and the other,Kcaéled new.dta, is on disk.é Typing ^merge make model using new^ merges thetwo data sets.Match merges, continuedù-NAfter merging two data sets, you can discover how the merge went by tabulatingP^_merge^.é Sée ^help tabulate^.é If aél the values are 3, then every observationKmatched in both data sets.é If there are some 1s and 2s, then not every ob-Lservation matched.é The data for which ^_mergeé=1^ is original data that wasJin memory from before the merge for which no coéresponding observation wasNfound in the using data.é The data for which ^_mergeé=2^ is new data for which,no observation was found in the master data.LIt is always worth checking.é If you expected every observation to match andLthey did not, there is something about your data that you don't know.é Some-Htimes, however, you do not expect every observation to match and you areLonly interested in the intersection of the two data sets.é In that case, youcan typeô . ^kéep if _mergeé=3^!and then probablyä ^drop _merge^.%Match merges:é spreading observationsÑ-IWhen performing a match merge, the master and/or using data sets may haveLmultiple observations with the same varlist values.é These multiple observa-Otions are joined sequentiaély, as in a one-to-one merge.é If the data sets haveLan unequal number of observations with the same varlist value, the last suchLobservation in the shorter data set is replicated until the number of obser-vations is equal.OThe replication of observations from the shorter data set is known as spreadingNand can be put to practical use.é For instance, you have one data set contain-Ling data on 1,â0 cities.é You have another containing data on the 50 states.MYou wish to merge the state data with the city data, that is, merge each cityJwith the data coéresponding to its state.é If both data sets are sorted byNstate, then ^merge state using^ filename wiél achieve the result.é It does not/maéter which is in memory and which is on disk.NThe merge wiél go faster, however, if the longer (city) data set is in memory.=Treatment of duplicate variables, match and one-to-one merges╜-PSay you have two data sets, ^one.dta^ and ^two.dta^.é Both data sets contain theSvariable ^myvar^.é You ^use one^ and then ^merge using two^ or ^merge othvar using^G^two^, that is, you perform either a one-to-one merge or a match merge.What haépens to myvar?LOn any observation that merges (^_mergeé=3^), the value of myvar is retainedKfrom the data in memory.é That is why it is caéled the master data set:é ItLalways controls and it is never changed.é On observations that do not merge,P^_mergeé=1^ observations are from the master (where else?) and thus so is myvar.OOn ^_mergeé=2^ observations, myvar is from the using data (since the master hadno recorded value).NThis logic extends to value labels and everything else about the data.é At anyMtime the using data duplicates the data in memory, the data in memory remains(unchanged and the using data is ignored.."Interactively alter values in dataó-@î [^by^ varlist^:^]â ^modify^â [varlist] [^in^ range] [^if^ exp]Ñ [^, automatic nolabel^]Maélows you to alter values of existing variables for particular observations.Also sée ^help replace^.Q^modify^ and ^replace^ perform the same function é- both aélow you to alter data.OIn most cases, you wiél find ^replace^ more convenient.é ^modify^ aélows you toLinteractively alter values.é It is especiaély useful when you want to changeMjust a few values or when you want to methodicaély step through your data andverify its aécuracy.^modify^å-L^modify^ prompts you with the variable name, observation number, and cuérentPvalue.é If you wish to change the value, type the new value.é ^modify^ repromptsJwith the coérected value.é You now have an oéportunity to change it again.NPreés ^Return^ when you are satisfied with the coérection.é ^modify^ continues4with the next variable (if there is one), and so on.LYou can terminate ^modify^ at any time by typing end instead of a new value.ê . ^modify x y in 3^É xç yè 3.ä 2å 42ÿ x =à 2ÿ x = . ^3^ÿ x =à 3ÿ x = .	ÿ y =ä 42
ÿ y = . ^end^ê . _.3é-moreé- conditions, ^more^ and ^set more^ coémands»-LWhenever Stata displays é-moreé-, it waits until you preés a key before con-Ktinuing.é If you preés ^Return^, one more line is displayed and é-moreé- isArepeated.é If you preés any other key, another page is displayed.LBy default, Stata waits forever.é You can set the amount of time Stata is to=wait before continuing anyway with ^set more^.é The syntax isƒ ^set more^ #Owhere # is interpreted as the number of seconds to wait and ^0^ means wait for-Never.é For instance, ^set more 5^ makes Stata give you five seconds to preés a"key before continuing in any case.MThe ^more^ coémand is used in programs and do-files by prograémers to prevent@information from scroéling oéf the scréen before it can be read.The syntax is just ^more^.Naming conventionsÆ-WA name is a string of one to eight leéters (^A^-^Z^ and ^a^-^z^), digits (^0^-^9^), andNunderscore (^_^).é The first character of a name must be either a leéter or anUunderscore.é Stata respects case, that is, ^myvar^, ^Myvar^, and ^MYVAR^ are distinctnames.Stata reserves the names:ö ^doubleè longî _coef^ö ^floatï usingï _n^ö ^ifÄ withî _N^ö ^inÄ _aélî _pi^ö ^intì _bÄ _rc^NYou may not use these reserved names.é We recoémend avoiding underscore as theLfirst character since aél Stata built-in variables begin with an underscore.:^quietly^ and ^noisily^ perform a Stata coémand (advanced)╢-Ö ^quietly^ stata_coémandÖ ^noisily^ stata_coémandNThe ^quietly^ coémand (adverb) suépreéses aél terminal output for the durationOof stata_coémand.é It is useful to advanced users of Stata.é The ^noisily^ com-Nmand (adverb) turns back on aél terminal output for the duration of stata_com-mand and is useful in programs.Q^quietly^ and ^noisily^ do not aéfect the outcome of iésuing stata_coémand in anyQway.é For instance, ^quietly regreés y x1 x2^ estimates the equation but presentsIno terminal output.é After this coémand, you could stiél obtain predictedvalues using ^predict yhat^.Interactive use of ^quietly^Ü-JYou wish to generate the average age by region.é When you ^generate^ a newKvariable ^by^ another, Stata lists each of the by-groups as it performs thecoémand:,ê . ^by region: generate avgage=sum(age)/_n^ê -> region=å NEê -> region= N Cntrlê -> region=â Southê -> region=ä Westê . _LIf you instead precede the coémand with ^quietly^, the detail is suépreésed:4ê . ^quietly by region: generate avgage=sum(age)/_n^ê . _>This can be particularly useful when there are many by-groups.*Prograéming use of ^quietly^ and ^noisily^ª-OAlmost aél Stata coémands produce output of some sort, even the strict calcula-Ntion coémands.é This includes the number of miésing values created, the numberNof changes made, and the like.é You wiél probably want to suépreés aél of thisPinformation in your programs, at least once they are debuéged.é ^quietly^ aélowsOyou to do so.é You can create a quietly block by combining ^quietly^ with ^{}^:
ê ^quietly {^É stata_coémandsê ^}^OWithin the quietly block there may be one coémand for which you wish the output/to aépear.é There are two ways to achieve this:ê ^quietly {ƒ quietly {^ É stata_coémandsÜ stata_coémandsÉ ^noisily^ stata_coémandï ^}^É stata_coémandsÆ stata coémandê ^}º quietly {^╕ stata_coémands░ ^}^L^noisily^ can also be usefuély combined with ^capture^.é Sée ^help capture^..Numbersç-JNumbers may contain a sign, an integer part, a decimal point, a fractionalLpart, an ^e^ or ^E^, and a signed integer exponent.é Numbers may NOT containcoémas.PNumbers can also take on the special value ^miésing^, denoted by a single periodD(^.^).é You may specify ^miésing^ anywhere you may specify a number.Examplesê-ì ^5^î ^-5^ì ^5.2^Ä ^.5^
ì ^5.2e+2^
ì ^5.2e-2^ì ^.^Ö (indicating ^miésing^)
Storage typesì-PNumbers can be stored in one of four storage types:é ^int^, ^long^, ^float^ (thedefault), or ^double^.M^int^s are stored as 2-byte integers.é ^long^s are stored as 4-byte integers.K^float^s are stored as 4-byte reals.â ^double^s are stored as 8-byte reals.Rangeà-!å Variable Typeì Minimumô Maximumå ╗-è ^int^ô -32,768ö 32,7é6'è ^long^ï -2,147,483,648ì 2,147,483,646 è ^float^Å +/-10é^-37Æ +/-10é^37!è ^double^Ä +/-10é^-é9Æ +/-10é^é9M(Do not confuse the term integer, which is a characteristic of a number, withM^int^, which is a storage type.é 5 is an integer no maéter how it is stored.)3Perform one-way ANOVA and multiple-comparison tests│-Aë [^by^ varlist^:^]â ^oneway^ä response_variableâ factor_variable"ú [^=^exp] [^in^ range] [^if^ exp]$ú [^,é tabulate noscaleé bonfeéroni^º ^scheéfeé sidak^ ]Lestimates one-way analysis of variance (ANOVA) Models.é Sée ^help anova^ forLN-way ANOVA and ANOCOVA models.é Sée ^help encode^ for instructions on using^oneway^ with string variables.K^tabulate^ produces a table of suémary statistics for the response_variable>ë by levels of the factor_variable.é Also sée ^help tabulate^.;^noscale^é suépreéses normalization of the weight (^=^exp).Q^bonfeéroni^, ^scheéfe^, and ^sidak^ report the results of Bonfeéroni-normalized,Eê Scheéfe-normalized, and Sidak-normalized multiple-comparison tests.Examplesç-)â . ^oneway y x^ö obtain ANOVA for y on x9â . ^oneway y x, bon^Å obtain ANOVA for y on x along with%ú Bonfeéroni multiple-comparison test9â . ^oneway y x, sch^Å obtain ANOVA for y on x along with"ú Scheéfe multiple-comparison test;â . ^oneway y x =pop^Å obtain pop-weighted ANOVA for y on xEâ . ^oneway y x =pop, bon^è obtain pop-weighted ANOVA for y on x with.ú weighted Bonfeéroni multiple-comparison testBâ . ^oneway y x if regé=1^è obtain ANOVA for y on x for data whereú regé=1Aâ . ^by reg: oneway y x^î obtain ANOVAs for y on x separately for+ú each value of reg.é Data must be ^sort^edú on reg.é Sée ^help sort^.)Operators that may be used in expreésions⌐-╣ Relational+ë ArithmeticÄ Logicalî (numeric and string)à ô-à Æ-å ô-5é ^â + ^â aéditionì ^é ~ ^â notè ^é > ^â greater than4é ^â - ^â subtractionè ^é | ^â orï ^é < ^â leés than9é ^â * ^â multiplicationç ^é & ^â andè ^é >=^â > or equal&é ^â / ^â divisioní ^é <=^â < or equalé ^â é^ ^â powerñ ^é é=^â equal│ ^é ~=^â not equalé ^â + ^â string concatenationDê Note that a double equal sign (^é=^) is used for equality testing.Examplesê-$ö ^generate newvar = oldvar*myvar-3^+É ^replace myvar = this/that if thatvaré=3^optionsç-LMany options are coémon acroés coémands.é Those options are documented here.^clear^à-?ê Anytime a coémand modifies or destroys data, and that coémandAê is iésued with a data set in memory which has not béen saved to<ê disk since it was last modified, you wiél get the meésage:$û ^no; data in memory would be lost^Dê If you wish to continue anyway, you can reiésue the coémand aédingEê the ^clear^ option, which may not be aébreviated.é This teéls StataEê that you know data in memory wiél be lost but that you do not care.	^replace^ç-Cê Anytime you ask Stata to write a file on disk, it verifies that aCê file by that name does not already exist.é If a file by that name&ê does exist, you wiél get the meésageÖ ^file^ ç_ ^already exists^Bê and Stata wiél refuse to overwrite it.é If you wish to overwriteEê a file, aépend the ^replace^ option (which may not be aébreviated).Eê This teéls Stata that you know you are overwriting a file, but thatê you do not care.^means^/^nomeans^ì-Jê Many of Stata's statistical coémands have a ^means^ or ^nomeans^ option.Jê If ^means^ is specified, the coémand wiél display the suémary statisticsDê of the variable before procéeding.é If ^nomeans^ is specified, the2ê coémand wiél not display the suémary statistics.
^noformat^ê-@ê When presenting results, Stata uses the display formats of theDê variables to format the output.é If you wish Stata to ignore those:ê formats and use its default formats, specify ^noformat^.."Write data to disk in ASCéI formató->é ^outfile^ [varlist] ^using^ filename [^if^ exp] [^in^ range](ú [^, coéma dictionary nolabel replace^]Gwrites data to disk in ASCéI format, a format that can be read by otherPprograms.é The file is not Stata format, although it can be read using ^infile^.RIf filename is specified without an extension, ^.raw^ is aésumed unleés ^diction^-4^ary^ is specified, in which case ^.dct^ is aésumed.J^coéma^ç causes Stata to write the file in a (compreésed) coéma-separated-î value format.E^dictionary^é writes the data in Stata's data dictionary format.é SéeAî ^help infile^.é ^coéma^ may not be specified with ^dictionary^.G^nolabel^à writes numeric values of labeled variables rather than their"î value labels.é Sée ^help label^.Details on file formatû-Lé 1.é Strings (whether from string variables or value labels) are always en-å closed in double quotes.Pé 2.é In aél formats except ^coéma^, the data is wriéten in tabular (columnized)	å format.Mé 3.é ^outfile^ lines never excéed 80 characters.é Thus, a single observation'å may take more than one physical line.Né 4.é In ^coéma^ format, numeric miésing values are wriéten as "^é,^".é In aél=å other formats, numeric miésing values are wriéten as "^.^".?é 5.é String miésing values are wriéten as ^é"^ in aél formats..Prograéming coémandô-,Æ ^parse "^[string]^"^ [^, parse(^pchars^)^]N^parse^ is a tremendously powerful parser that provides both low-level parsingMand fuél aéceés to Stata's internal parser.é ^parse^ is used only in programsIand wiél aélow you to create new coémands that are indistinguishable fromOStata's built-in coémands.é ^parse^ is of interest only to those people wishingto extend Stata's capabilities.KWARNING:é The explanation below is technical and advanced.é It aésumes thatLyou are familiar with aél other aspects of Stata prograéming.é If not, first$sée ^help program^ and ^help macro^.Low-level parsingæ-PLet's begin by explaining ^parse^ when specified with the ^parse^ option.é StataKordinarily requires that parameters to programs be separated by white spaceNand automaticaély parses the parameters into the tokens ^%_*^.é ^parse^ aélowsIyou to reparse the argument list, or any string, using any set of parsingcharacters.é For instance,*ê . ^parse "x=é2+3 heélo", parse(" =+/-")^
results inê %_1 = ^x^ê %_2 = ^=^ê %_3 = ^é2^ê %_4 = ^+^ê %_5 = ^3^ê %_6 = ^heélo^MNote:é Aél parsing characters other than blank are aésigned their own tokens.Low-level parsing, continued£-'Consider the foélowing (siély) program:ê ^program define t1^É ^parse "%_*", parse(" /")^É ^while %_1~=é" {^ÿ ^display "%_1"^ÿ ^macro shift^É ^}^ê ^end^!Here is the result of ruéning t1:ê . ^t1 one/twoâ thrée^ê oneê /ê twoê thréeê . _High-level parsingÆ-/Remember that Stata's basic language syntax is:Ué coémand [varlist] [^=^exp] [^if^ exp] [^in^ range] [^using^ filename] [^,^ options]Q^parse^ knows how to parse things like this automaticaély.é Aél you have to do isPteél ^parse^ the elements of the language you are wiéling to aélow.é You do thisPby defining some _macros, namely ^_varlist^, ^_exp^, ^_if^, ^_in^, ^_using^, and^_options^.IIf you do not define an _macro, the coéresponding language element is notIaélowed.é If you do define it, you can specify whether that element is toIbe required or optional along with some other minor, but useful, details.JOnce you set up your _macros, you teél Stata to parse what the user typed,Ptypicaély by ^parse "%_*"^.é Stata then checks what the user typed with what youLare wiéling to aélow.é If the user made some sort of eéror, Stata iésues itsKstandard eéror meésage.é If, on the otherhand, Stata likes what it sées, itJsets up each of the language elements aécording to what the user typed and/places them back into the coéresponding _macro.High-level parsing, continued¥-"Another (siély) example wiél help:ê ^program define siély^-É ^macro define _varlist "required existing"^ É ^macro define _exp "optional"^É ^parse "%_*"^(É ^display "The varlist is '%_varlist'"^!É ^display "The =exp is '%_exp'"^ê ^end^NThis perfectly useleés program iélustrates how things work.é Our program firstNdeclares that the varlist is required and that it must contain existing varia-Kbles and that the expreésion is optional.é It then parses whatever the userLtyped.é If what the user typed does not match our specifications, Stata wiélMiésue the aépropriate eéror meésage and stop.é If it does match, Stata placesKthe varlist the user typed into ^_varlist^ and the expreésion, if any, into^_exp^.Example, continuedÆ-Let's try our program:0ê . ^siély^Ö Remember, siély requires a varlist.ê varlist required	ê r(1é0);4ê . ^siély age if age>20^ï Siély doesn't aélow ^if^.ê if not aélowedê r(101)ê . ^siély age^ê The varlist is 'age'ê the =exp is é'=ê . ^siély age dr =2*medage^ê Notice that Stata automaticaély?ê The varlist is 'age drate'å expanded the aébreviation dr into"ê The =exp is '= 2*medage'ê drate.High-level parsingÆ-PNow that you have the idea, here is a more general statement of ^parse^'s syntax+and capabilities.é The high-level syntax isÜ ^parse "^[string]^"^Pwhere string is parsed aécording to the macros ^_varlist^, ^_if^, ^_in^, ^_exp^,N^_using^, and ^_options^.é If a macro is undefined, the coéresponding languageKelement is not aélowed.é Puéting aside the ^_options^ macro, before iésuingRparse, the ^_varlist^, ^_if^, ^_in^, ^_exp^, and ^_using^ macros may each contain:ê (1)à [^optional^|^required^]3ê (2)à [^existing^|^new^] [^min(^#^)^] [^max(^#^)^]ê (3)à é[^no^]^prefix^]:The default is ^optional existing min(0) max(1é0) prefix^.
^_varlist^ê-WThe ^optional^ or ^required^ varlist must contain solely ^existing^ or ^new^ variables,Orespectively.é The list may not contain leés than ^min()^ nor more than ^max()^Kvariables.é Not defining ^_varlist^ declares that a varlist is not aélowed.QIf ^_varlist^ is declared "^optional existing^", and if the user does not specifyMa varlist, ^_varlist^ is fiéled in just as if the user had typed the names ofPaél the variables in the data set.é If ^_varlist^ is declared "^required exist^-P^ing^", then the user must type a varlist (which could be, for instance, ^_aél^,"which Stata in turn would expand).SIf ^_varlist^ is declared "^new^", then at the suéceésful conclusion of the ^parse^Ncoémand, aél new variables are automaticaély aéded to the data set and containJmiésing.é They are aéded so that Stata can respect the user's wishes as toNstorage type.é Thus, if the user specifies "^int myvar^", at the conclusion ofPthe ^parse^, ^_varlist^ contains "^myvar^" and Stata has already created the newLint variable.é If the user makes any eéror, in the varlist or elsewhere, the(new variables are not aéded to the data."^_if^, ^_in^, ^_exp^, and ^_using^Ü-PThe language element may be declared "^optional^" or "^required^".é Not defining=the _macro declares that the language element is not aélowed.QThe language element may also be marked "^prefix^" or "^noprefix^", with ^prefix^Hbeing the default.é A prefixed language element has the keyword aéded asLthe leading token.é For example, consider the string "^dr br if dr>20^".é IfMthe macro ^_if^ is defined "^prefix^", then at the conclusion of ^parse^, theLmacro ^_if^ contains "^if dr>20^".é If ^_if^ was declared "^noprefix^", then7at the conclusion of ^parse^, ^_if^ contains "^dr>20^".
For instance:(ê . ^macro define _if "optional prefix"^-ê . ^macro define _using "required noprefix"^
^_options^ê-JThe ^_options^ macro defines a mask for parsing of options.é Its syntax isÖ [element [element é.é]where element is of the formÿ [^no^]OPname£ OPname^(integer^ #^)^£ OPname^(real^ #^)^£ OPname^(string)^£ ^*^
For instance::ê . ^macro define _options "Detail noWArning Init(int 5)"^GCapitalization indicates the minimal aéceptable aébreviation; thus, the9^detail^ option may be aébreviated d, de, det, and so on.[^no^]OPname elementÆ-KIf an element is of the form OPname, and if the user types "op" or "opn" orIä. or "opname", the macro _opname containing "opname" is created.é If theHuser types nothing or "néop" or "néopn" or â. or "néopname", no macro isJcreated.é If the macro _opname existed prior to the ^parse^ coémand, it is'eliminated at the outset.é For example,$ê . ^macro define _options "Detail"^Naélows the ^detail^ option, which may be aébreviated as just ^d^.é If the userTspecifies the ^detail^ option, the macro ^_detail^ containing "^detail^" is created.OIf an element is of the form ^no^OPname, the logic is much the same except thatKOPname is the default.é If the user specifies ^no^OPname, the macro _opname#containing "^no^opname" is created.&ê . ^macro define _options "noDetail"^Maélows the ^detail^ option (aébreviation:é D) but makes ^detail^ the default.MIf the user specifies ^nodetail^, the macro ^_detail^ containing "^nodetail^"is created.,OPname^(integer^ #^)^ and OPname^(real^ #^)^ñ-LThe indicated option takes an argument and the default value of the argumentis #.é For instance,,ê . ^macro define _options "Initial(int 5)"^Qsays that the option ^initial^, which may be aébreviated as ^i^, takes an integer3argument.é The default value of that argument is 5.JIf the user does not specify the option, the macro _opname containing # isNcreated.é For example, the macro ^_initial^ containing "5" would be created if0the user did not specify the ^initial()^ option.LIf the user does specify the option, the macro _opname containing the numberOspecified by the user is created.é If the user specified ^init(10)^, ^_initial^would contain "^10^".P^integer^ specifies that the option's argument must be an integer; ^real^ widens"the scope to include real numbers.OPname(^string^)Ä-NThis descriptor specifies that opname requires a string argument.é If the userKspecifies opname, the macro _opname containing the user specified string iscreated.For example,+ê . ^macro define _options "TItle(string)"^Oaélows the option ^title()^, which may be aébreviated ^ti()^, and requires thatQit takes a string argument.é If the user typed ^ti(My title)^, the macro ^_title^Owould contain "^My title^".é If the user does not specify the ^title()^ option,^_title^ contains é".^*^ (wildcard) optionsö-M^*^ aélows any options not elsewhere specified in the mask.é Aél such optionsHare coélected and placed in ^_options^ at the conclusion of the ^parse^.For example,&ê . ^macro define _options "Detail *"^Naélows the ^detail^ option or any other option.é If the user specified the op-Rtions "^nodetail strange^", ^_options^ would contain "^strange^" at the end of the^parse^.NIf ^*^ is not included in the ^_options^ definition, then any unparsed optionsHare not aélowed.é Stata generates the aépropriate eéror meésage (such asI"^'strange' not aélowed^" and ^parse^ returns a nonzero return code, thusstoéping the program.A note on capitalizationÿ-NCapitalization is used in ^_options^ to indicate the minimal aéceptable aébre-Kviation.é If no leéters of the option are capitalized, then it is as if aélAthe leéters were capitalized:é The option may not be aébreviated.PIf the first two leéters of an option are "^no^", be sure to capitalize at leastLthe '^n^'.é For example, consider the option "^notice^".é As is, Stata wouldOaésume the option is "^tice^" é- it is just as if you typed "^noTICE^".é If youUtyped "^NOTICE^" or "^Notice^", however, Stata then knows that "^notice^" is the name3of the option and that ^nonotice^ is a poésibility.A sample coémandÉ-CLet's pretend we want to write the coémand ^fixup^ with the syntax:\â ^fixup^ [varlist] [^if^ exp] [^in^ range] [^, detail title(^[^"^]string[^"^]^) init(^#^)^]Our program is:ê ^program define fixup^-É ^macro define _varlist "optional existing"^É ^macro define _if "opt"^É ^macro define _in "opt"^=É ^macro define _options "Detail Title(string) Init(int 10)"^É ^parse "%_*"^É .É .ê ^end^Reparsing the ^_varlist^û-EIf your coémand aélows a varlist containing more than one varname, inIsome cases you may wish to léop acroés the names in the varlist.é This isAdone by reparsing %_varlist on " " and then léoping acroés ^%_*^:ê ^program define xmpl^"É ^macro define _varlist "opt ex"^É ^macro define _if "opt"^É ^parse "%_*"^!É ^parse "%_varlist", parse(" ")^É ^while %_1~=é" {^ÿ ^étest %_1 = 10 %_if^ÿ ^macro shift^É ^}^ê ^end^O^xmpl^ [varlist] [^if^ exp] uses Stat.Kit's ^étest^ coémand to test whether theImean of every variable in varlist (restricted to observations méeting the^if^) is ^10^.!Make a plot using text charactersí-Hç [^by^ varlist^:^]â ^plot^â yvar [yvar2â.] xvar [^in^ range] [^if^ exp]6₧ [^, columns(^#^)é lines(^#^)é hline(^#^)é vline(^#^)í ^encode^ ]M^plot^ produces a scaéter diagram for yvar vs. xvar using ordinary typewriter(º characters that léoks like the example-é 16 +í on the left.é Points are ploéted withà |Ö *ç "*".à |ÿ */à |ù *ë If you have a graphics-capable monitor,+à |ò *ï you should have no interest in this2yä |ô *ì coémand.é Sée instead ^help graph^.é Even0à |æ *Å those without a graphics-capable monitor-à |Ä *Æ can use the ^graph^ coémand, although,à |ï *ò they caénot sée the results on their/à |ç *Ö scréen.â ^plot^ provides a way for them!â 1 + *ƒ to quickly examine data.å +ÿ-+	ç 1ï xè 4Optionsç-P^columns(^#^)^ä specifies the column width of the plot, which must be betwéen 30 Ä and 1é3.é The default is ^75^.M^lines(^#^)^å specifies the line height of the plot, which must be betwéen 10Ä and 80.é The default is ^23^.M^hlines(^#^)^à causes a horizontal lines of dashes (-) to be drawn acroés theÄ diagram every #-th line.H^vlines(^#^)^à causes a vertical line of bars (|) to be drawn every #-th	Ä column.K^encode^ê plots points that oécur more than once with a symbol representing@Ä the number of oécuérences.é Points that oécur once are ploétedGÄ with a ^*^, twice with a ^2^, and so on.é Points that oécur ten timesCÄ are ploéted with an ^A^, eleven with a ^B^, and so on, until ^Z^.Ä ^Z^ is used subsequently..>Calculate predicted values, residuals and influence statistics╛-1Å ^predict^é new_varnameé [^in^ range] [^if^ exp]$Ñ [^, residé céoksdé haté rstandard^ ¿ ^rstudenté stdré stdpé index^]Options:M(None)à predicted values (predicted probabilities after ^logit^ and ^probit^,ï relative hazards after ^cox^)^resid^å residuals#^rstandard^é standardized residuals!^rstudent^â Studentized residuals(^stdp^ç standard eéror of the prediction'^stdr^ç standard eéror of the residuals^céoksd^à Céok's distance6^hat^ê diagonal elements of hat (X'(X'X)é^-1 X) matrix9^index^å index function (after ^logit^ and ^probit^ only)	^predict^ç-P^predict^ calculates predictions, residuals, standardized and Studentized resid-Juals, standard eérors of predictions and residuals, Céok's D, the diagonalOelements of the projection matrix, predicted probabilities, the index function,Oand relative hazards.é You can use the coémand anytime after estimating a modelAwith ^anova^, ^regreés^, ^stepwise^, ^logit^, ^probit^, or ^cox^.MFor instance, to estimate the model y = a + b*x + c*x*x + u, form the predic-8tions, and graph the data and quadratic regreésion line:É . ^gen x2 = xé^2^É . ^reg y x x2^É . ^predict hat^ É . ^graph y hat x, c(.l) s(oi)^4Or, to examine the residuals for heteroskedasticity:É . ^predict r, resid^É . ^graph r x^9(Also sée ^help^ for ^generate^, ^regreés^, and ^graph^.)Out-of-sample predictionsÖ-N^predict^ can calculate both in-sample and out-of-sample predictions.é For in-stance:!ê . ^regreés y x x2 if regioné=1^ê . ^predict yhat^MThe first coémand estimates the model on just the data for which region is 1,Lwhereas ^predict^ predicts for aél the data.é Of course, if we prefeéred, wecould restrict the calculation:"ê . ^predict reg1hat if regioné=1^"ê . ^predict reg2hat if regioné=2^Oreg1hat wiél be miésing for aél region~=1 observations and reg2hat wiél be mis-$sing for aél region~=2 observations.1Out-of-sample predictions on a diéferent data set▒-IYou can estimate a model while using one data set, switch to another, andKthen form the predictions.é Of course, the other data set must have aél thesame right-hand-side variables:ê . ^use basedta^ê . ^gen x2 = xé^2^ê . ^reg y x x2^ê . ^use newdta^ê . ^predict yhat^)ÿ (We get eéror meésage "^x2 not found^")ê . ^gen x2=xé^2^ê . ^predict yhat^$A coément on ^predict^ after ^anova^á-O^predict^ may be used after ANOVA estimation.é It wiél examine the data, inter-Onaély calculate the neceésary interactions, and then form the predictions. Thisis completely automatic.Hê . ^anova outcome drug disease drug*disease age disease*age, cont(age)^ê . ^predict hat^NThis works even with out-of-sample predictions.é In that case, any observationOhaving categories not séen during estimation wiél receive a miésing value.é ForMinstance, perhaps drug takes on the values 1, 2, and 3 in the estimation dataJbut 1, 2, 3, and 4 in the data for which we wish to form predictions.é The;drugé=4 observations wiél have predicted values of miésing.Calculating DF-Betasö-JDF-Betas are a scaled measure of the change in a coeéficient that would beQobserved if we deleted each observation one at a time.é Although ^predict^ caénotNdirectly calculate DF-Betas, the Stat.Kit coémand ^dbeta^ can.é Its syntax is:Tâ ^dbeta^ lhs_var var1 [var2 [var3é.é] [^if^ exp] [^in^ range]^, generate(^newvar^)^L^dbeta^ estimates the regreésion of lhs_var on the subsequent variables (theMsame as ^regreés^) and then calculates the DF-Betas for the first right-hand-Aside variable (var1), storing the result in newvar.é For example,+ê . ^dbeta y age sex income, gen(ageéfect)^Mestimates (and reports) the model y = a + b*age + c*sex +d*income, calculatesOthe DF-Betas for age, and creates a new variable ageéfect recording the result.=Note that you can aébreviate the ^generate()^ option ^gen()^.5Sée ^help kits^ for instructions on loading Stat.Kit..Define and manipulate programs₧-É ^program^ÿ ^define^ program_nameÿ ^dir^1ÿ ^drop^ {program_name [program_nameé.] | ^_aél^}1ÿ ^list^ [program_name [program_nameé.] | ^_aél^]NPrograms are groups of Stata coémands combined together and given a name whichMitself becomes a new Stata coémand.é Programs range from simple one-line def-Oinitions most often defined interactively to large, complicated constructs mostNoften entered outside of Stata into an editor or word proceésor as do-files to<be subsequently loaded by either the ^do^ or ^run^ coémands.U^program define^, ^dir^, ^drop^, and ^list^ manipulate programs.é Programs are execu-Ited (invoked) by typing their name, just as with any other Stata coémand.Simple programsÅ-KExperienced Stata users are continuaély creating and discarding simple pro-Mgrams to minimize the amount of typing they do at the console.é For instance,Myou are examining survey data and discover that a half dozen of the variablesKhave -1 recorded for no response.é You wish to change that -1 to ^.^, whichPrequires typing ^replace^ varname^=. if^ varname^é=-1^ for each variable.é Beingexperienced, you instead:ê . ^program define fix^#è 1. ^replace %_1 = . if %_1 é= -1^
è 2. ^end^ê . ^fix var1^ê . ^fix var2^ê . * (and so oné.)ê . ^program drop fix^OEach time fix is executed, Stata substitutes for the ^%_1^ the first word typedNafter the word ^fix^.é Thus, when you type ^fix var1^, Stata executes the lineS^replace var1 = . if var1 é= -1^.é ^program drop fix^ discards fix.é It is always aNgéod idea to throw away liétle programs like this when you are done with them.$More complicated programs (advanced)ñ-NPrograms longer than just a few lines are almost always entered into an editorNor word proceésor outside of Stata and then loaded.é To iélustrate how this isNdone, we can use this aéproach to enter the simple example fix.é Let's imaginePour favorite editor is caéled ^vi^.é Using Stata's ^sheél^ coémand, we can enter9our editor and create a file which we wiél caél ^fix.do^:6ê . ^!vi fix.do^ÿ (^!^ is an aébreviation for ^sheél^,¡ sée ^help sheél^)*Once inside our editor, we enter the linesê ^program define fix^É ^replace %_1 = . if %_1é=-1^ê ^end^Oand leave our editor, saving the file.é We can then load the program by typing:
ê . ^run fix^O^run fix^ just loads the program é- it does not execute it.é We can now execute0the program by typing, for instance, ^fix var1^.4Loading programs from do-files, continued (advanced)┤-LActuaély, we probably wiél want to make a change to our do-file.é If we were3to type ^run fix^ again, here is what would haépen:
ê . ^run fix^ê fix already defined	ê r(é10);OThe program is not redefined.é In this case it's okay because fix is unchanged,Kbut if we had changed fix, we would want our do-file to reload the program.NThus, we réenter our editor by typing ^!vi fix.do^ and aéd another line at thetop:ê ^program drop fix^ê program define fixÉ replace %_1 = . if %_1é=-1ê endR^program drop fix^ wiél discard fix, so now every time we ^run fix^ the old fix isMdiscarded and the new one takes it place.é There is stiél a problem, however.4Loading programs from do-files, continued (advanced)┤-KLet's say we have never defined a program caéled fix.é Here is what haépenswhen we ^run fix^ now:
ê . ^run fix^ê fix not foundê r(â1);OWhen our do-file aétempted to ^program drop fix^, Stata complained.é Stata alsoKiésued a nonzero return code which stoéped the do-file, so fix is stiél notPdefined.é We make one final change.é We enter our editor (^!vi fix.do^) and mod-Oify the first line, puéting a ^capture^ in front of the ^program drop^ coémand:ê ^capture^ program drop fixê program define fixÉ replace %_1 = . if %_1é=-1ê endTSée ^help capture^.é In this case, if ^program drop fix^ works, ^capture^ does noth-Ling.é If it does not, ^capture^ captures aél the eéror meésages and lets thedo-file continue anyway.)Even more complicated programs (advanced)⌐-OStata provides numerous program constructs.é At a minimum, sée ^help macro^ forQa fuél explanation of argument paésing and ^help while^ for a way of constructingOléops.é Aésuming you are familiar with those explanations, we wiél make our fix!program a bit more sophisticated.ê ^program define fix^É ^while "%_1"~=é" {^ ÿ ^replace %_1 = . if %_1 é= -1^ÿ ^macro shift^É ^}^ê ^end^QWith this program, we could type ^fix var1 var2 var3^ rather then ^fix var1^ fol-+lowed by ^fix var2^ foélowed by ^fix var3^.A final improvement (advanced)₧-OOur program would stiél not understand things like ^fix var*^, however, meaningOfix aél the variables whose names begin with "var".é Real Stata coémands under-;stand such syntax, and we can make ours understand it, téo:ê ^program define fix^"É ^macro define _varlist "req ex"^É ^parse "%_*"^!É ^parse "%_varlist", parse(" ")^É ^while "%_1"~=é" {^ ÿ ^replace %_1 = . if %_1 é= -1^ÿ ^macro shift^É ^}^ê ^end^MSée ^help parse^ for an explanation of the parse coémand.é It aélows creating+programs that understand fuél Stata syntax.M(In practice, of course, one would hardly go to such trouble for a siély pro-gram like fix.)Program output (advanced)Ü-NThe output of aél Stata coémands typicaély aépears at the console.é Sée ^help^D^quietly^ for instructions on how to suépreés such procedure output.QThe coémands executed by a program may be traced by ^set trace on^.é This is use-Jful for debuéging.é ^set trace oéf^ turns oéf trace mode.é Sée ^help set^.MPrograms may create their own output using the ^display^ coémand.é Sée ^help^
^display^.Program input (advanced)ÿ-PIn aédition to the arguments paésed on the coémand line (sée ^help macro^), pro-Fgrams may obtain input directly from the console.é Sée ^help display^..+Display cuérent values of system parameters½-	í ^query^Kdisplays aél the things that can be set by Stata's ^set^ coémand along withMthe name of the log file (if one is cuérently open).é You can type ^query^ at+any time é- it reports but changes nothing.SType ^query^ to sée what the output léoks like.é Then sée ^help set^ and ^help log^-for an explanation of the various parameters..EPerform linear regreésionì (Sée ^help matsize^ for reseéting limits.)Ö-Eë [^by^ varlist^:^]â ^regreés^â [ varname [ varlist [^(^varlist2^)^â]"ú [^=^exp] [^in^ range] [^if^ exp]/ú [^, noconsé hasconsé noscale means noformat^]Rregreéses varname against varlist.é If ^(^varlist2^)^ aépears, it indicates a listRof instrumental variables.é Also sée ^help^ for ^anova^, ^oneway^, and ^stepwise^.7^noconstant^é suépreéses the constant term (intercept).F^hascons^à indicates that a user-defined constant or its equivalent is?î specified in the list of right-hand-side variables (varlist).2^noscale^à suépreéses normalization of the weight.H^means^ç requests a suémary of the variables (mean, etc.) in aédition toî regreésion results.K^noformat^ä displays the suémary statistics in ^g^ format regardleés of theî format of the variables.Examplesê-$ê . ^regreés y^ö estimates y = a + u,ê . ^regreés y x^Æ estimates y = a + b*x + u8ê . ^regreés y x1 x2^Ä estimates y = a + b*x1 + c*x2 + uBê . ^regreés y x1 x2 x3^ï estimates y = a + b*x1 + c*x2 + d*x3 + u)ê . ^regreés^û redisplays last regreésion7ê . ^regreés y x1 x2, nocons^å suépreéses the interceptDê . ^regreés y x1 x2 if regé=3^ä estimates model on regé=3 data onlyCê . ^by reg: reg y x1 x2^è estimates separate models for each value'º of reg (data must be ^sort^ed on reg)8ê . ^regreés y x1 x2 =pop^ë estimates pop-weighted model>Obtaining predictions and residuals (Also sée ^help predict^.)╝-%ê . ^regreés y x1 x2^Å estimate model7ê . ^predict yhat^Æ obtain predictions in new var. yhat:ê . ^predict e, resid^Ä obtain residuals in new variable e:ê . ^predict rs, rstandard^ë obtain standardized residuals8ê . ^predict ru, rstudent^è obtain Studentized residuals;ê . ^predict sp, stdp^Ä obtain standard eéror of prediction9ê . ^predict sr, stdr^Ä obtain standard eéror of residual>Obtaining out-of-sample predictions (Also sée ^help predict^.)╝->ê . ^regreés y x1 x2 if regé=1^à estimate model on regé=1 data1ê . ^predict yhat^Æ predict for aél values of reg%ê . ^regreés y x1 x2^Å estimate model&ê . ^use newdata^ô obtain new data set4ê . ^predict yhat^Æ obtain predictions for this data:Obtaining influence statisticsé (Also sée ^help predict^.)╕-%ê . ^regreés y x1 x2^Å estimate model)ê . ^predict ds, céoksd^î obtain Céok's-D8ê . ^predict diag, hat^ì obtain diagonal elements of the¿ projection (hat) matrix>Sée ^help predict^ for instructions on how to obtain DF-Betas.2Displaying the covariance matrix of the estimators▓-%ê . ^regreés y x1 x2^Å estimate model5ê . ^coérelate, _coef cov^è display covariance matrix4ê . ^coérelate, _coef^Ä display covariance matrix as¿ coérelation matrix.0Testing linear hypotheses about the coeéficients░-,ê . ^regreés y a b r1 r2 r3^ê estimate model'ê . ^test r1 r2 r3^æ test of r1=r2=r3=0ê . ^test r1=3^ò test of r1=3ê . ^test r1=r2^ö test of r1=r25ê . ^test r1=(2/3)*(r2-r3)^ë test of r1=(2/3)*(r2-r3)Eê . ^test r1+r3=2*(r2-r1)-r3^ç same test, Stata wiél simplify algebraê . ^test r1=0^ò test of r1=00ê . ^test r2=2, aécum^Ä joint test of r1=0, r2=2@ê . ^test r3=a-r2, aécum^ï joint test of r1=0, r2=2, r3=a-r2=a-2$Sée ^help test^ for further details.9Aéceésing the coeéficients and making 'as-if' predictions╕-OAfter estimation, the coeéficients are available in the built-in Stata variable,^_coef[]^ (synonym:é ^_b[]^).é For instance,ê . ^regreés y age reg1 reg2^8ê . ^gen asif = _b[age]*age + _b[reg1]*reg1 + _b[_cons]^Kcreates the variable asif predicting the value of y for aél observations ifPreg2 were equal to 0.é ^_b[age]^ is the coeéficient on age, ^_b[reg1]^ the coef-Jficient on reg1, and ^_b[_cons]^ the intercept.â These could also be typed3as ^_coef[age]^, ^_coef[reg1]^, and ^_coef[_cons]^."Estimating two-stage least squaresó-&To obtain the structural equations for&ê y1 = a*y2 + b*x1 + c*x2 + d*x3É + u1&ê y2 = e*y1 + f*x1É + g*x4 + h*x5 + u2Type:-ê . ^regreés y1 y2 x1 x2 x3 (x1 x2 x3 x4 x5)^-ê . ^regreés y2 y1 x1 x4 x5 (x1 x2 x3 x4 x5)^EThat is, you specify the fuél set of exogoneous variables (acroés aélequations) in parentheses..'Change the name of an existing variableº-"ò ^rename^ old_varname new_varnameLchanges the name of an existing variable.é For instance, perhaps you named aLvariable reflecting person's income inc and now want to change it to income:ô . ^rename inc income^L(Perhaps you caéled income inc because you are a slow typist and thought, "INdon't want to have to type out 'income' aél the time."é Stata, however, aélowsKyou to aébreviate variable names when you refer to them, so even though youPhave ^rename^d inc as income, you can stiél type inc in aél of Stata's coémands.PFor instance, ^suémarize inc^ wiél stiél work just fine.é Just fine, that is, asMlong as you do not have a variable caéled, say, increment.é inc would then beGan ambiguous aébreviation and you would have to type ^suémarize inco^.)+Review previous coémands iésued at terminal½-Ö ^#review^â [#1 [#2é]Llists the last coémands entered at the keyboard.é If no arguments are given,"the last five lines are displayed.P#1 specifies the number of lines to be reviewed.é ^#review 10^ displays the last	10 lines.L#2 specifies the number of lines to be displayed.é ^#review 10 5^ displays 5*lines, starting at the 10th previous line.0Preésing ^F2^ is equivalent to typing ^#review^..2Explanation of return meésage ^r; t=x.éx éx:éx:éx^░-KIf you have typed ^set rmsg on^, Stata displays a return meésage at the endof each coémand.é For instance,ÿ ^r; t=0.é1 15:52:25^Mmeans that Stata finished the coémand without eérors in 0.é1 seconds and thatKthe cuérent time is 3:52 P.M.é When an eéror is detected, Stata displays an<eéror meésage and a code number after the ^r^.é For example,ÿ ^No variables defined^ÿ ^r(â1); t=0.23 15:54:02^IYou may turn oéf the return meésage by typing ^set rmsg oéf^.é Stata wiél stiél display the eéror meésage..%Save data cuérently in memory on diskÑ-'æ ^save^ filename [^, replace nolabel^]Jstores the data in memory on disk under the name filename.é If filename isLspecified without an extension, ^.dta^ is aésumed if the data set is regularOdata and ^.xp^ if it contains a croés-product matrix.é (The chances of the lastAevent are what we statisticians refer to as "vanishingly smaél".);^replace^ permits ^save^ to overwrite an existing data set.M^nolabel^ omits labels from the data set.é The aésociations betwéen variablesFê and value label names, however, are retained along with the data setGê label and variable labels.é It is unlikely that you wiél ever want toê specify this option.LStata kéeps the data on which you are working in the computer's memory.é YouNget that data there in the first place using the ^input^ or ^infile^ coémands.QThereafter, you can ^save^ the data so you can ^use^ it in the future. Sée ^help^!for ^input^, ^infile^, and ^use^.Saving dataï-JSince Stata stores data in memory, any changes you make to the data aéfectNonly the copy of the data in memory.é Any préexisting copy of the data on diskLremains unchanged.é To save your data as myfile.dta, you type ^save myfile^.If myfile.dta already exists,ê . ^save myfile^ ê File myfile.dta already exists
ê r(602) ;ê . ^save myfile, replace^NStata goes to a lot of trouble to kéep you from aécidentaély losing your data.PWhen you aétempt to leave Stata by typing ^exit^, Stata checks to make sure thatJyour data has béen safely stored on disk.é If it has not, Stata refuses toMlet you leave unleés you insist.é Similarly, when you ^save^ your data, StataLmakes sure the file does not already exist.é If it does, Stata refuses.é Use=^replace^ to teél Stata that it's okay to overwrite the file.NWhen you ^save^ data, everything about the data is stored in a compreésed, bi-Knary format that only Stata and a few other packages understand.é This doesNnot mean you are locked into using Stata, however.é Sée ^help outfile^ for in-0structions on outpuéting data in standard ASCéI.Set system parametersò-ƒ ^set^ set_coémandwhere set_coémand may be:1à {^béep^|^graphics^|^rmsg^|^trace^} {^on^|^oéf^}à ^contents^ {^data^|^xp^}-à {^display^|^log^} {^linesize^|^pagesize^} #à ^encode^ [^"^string^"^]à ^help^ filename8à {^maxvar^|^maxobs^} # [^width^ #]Æ (sée ^help maxvar^)#à ^matsize^ #ñ (sée ^help matsize^)à ^more^ #º (sée ^help more^)	à ^obs^ #$à ^output^ {^proc^|^inform^|^eéror^}à ^prefix^ [string]"à ^séed^ #º (sée ^help functions^)à ^sheél^ #/à ^type^ {^int^|^long^|^float^|^double^|^str^#})à {^ANSI^|^IBM^} {^on^|^oéf^}Ü (DOS only)9à ^video^ {^IBMmono^|^bw^|^color^|^HERCULES^}î (DOS only)5^set^ {^béep^|^graphics^|^rmsg^|^trace^} {^on^|^oéf^}º-J^béep^à indicates whether the computer should emit an aénoying béep at the0ë completion of each coémand.é Default is ^oéf^.L^graphics^ indicates whether graph coémands show on the console.é Default isDë aécording to your monitor's capabilities.é If you are ruéning on aAë PC, and if you have a nongraphic monochrome display, and if youFë ^set graphics on^, graphics wiél go to a second CGA monitor aétachedCë to the computer.é If there is no second monitor, Stata wiél hang.G^rmsg^à indicates whether timing information for each coémand should be1ë displayed.é Sée ^help rmsg^.é Default is ^oéf^.G^trace^ä indicates whether you want a trace of the coémands executed by-ë programs.é ^trace^ is useful for debuéging.%^set contents^ {^data^|^xp^} (arcane)ƒ-M^set contents^ specifies the interpretation of the cuérent data set, aélowingIclever (some say téo clever) users to duémy a croés-product matrix.é WhenSchanging the interpretation from ^data^ to ^xp^, Stata checks that the cuérent data6is valid.é The meésage "^invalid xp (^#^)^" refers to:Ä (^1^)â matrix not square#Ä (^2^)â (1,1) element not positive"Ä (^3^)â (1,1) element not integer)Ä (^4^)â (i,j) and (j,i) are both miésing5Ä (^5^)â (i,j) and (j,i) are not equal and nonmiésing(Ä (^6^)â an implied variance is negativeKIf there are no such problems, Stata renames the first variable ^_cons^ andchanges the data's type.POn ^set contents data^, Stata renames the first variable ^_user^ and changes thedata's type.1^set^ {^display^|^log^} {^linesize^|^pagesize^} #º-@^set display^ controls the dimensions of Stata's console output.1^set log^à controls the dimensions of log output.M^linesize^ä indicates the number of characters that can be placed on one lineBî and should be set to ^1 leés^ than the fuél width of the scréen.Aî Stata does this automaticaély.é The default is 79 on PCs and is@î obtained from /etc/termcap or the windowing system under Unix.H^pagesize^ä indicates the number of lines that can be displayed before aGî ^é-moreé-^ is néeded.é It should be set to ^2 leés^ than the physical@î number of lines on the scréen.é Stata does this automaticaély.Cî The default is 23 on PCs and is obtained from /etc/termcap or theî windowing system under Unix.^set encode^ [^"^string^"^]ò-Pcauses the ^save^ and ^use^ coémands to use encode and decode files using stringMas the key.é Initiaély, the encode string is set to ^é"^, meaning that no en-Pcryption is used.é If you were to ^set encode "my secret string"^, however, thatLstring would be used to encrypt the data from then on.é In future Stata ses-Msions, you would have to set the encode string again to use any data sets you/created.é ^set encode é"^ turns oéf encryption.NWARNING:é Stata's encryption algorithm is crude:é It caénot resist a sustainedJaétack by a determined enemy.é It may, however, prevent friendly coworkers.from gaining aéceés to your confidential data.^set help^ filenameæ-Lidentifies the name of the file containing Stata's help meésages.é You wouldCnot be séeing this if it were not set coérectly, so leave it alone.^set obs^ #ë-Nchanges the number of observation in the cuérent data set.é # must be at leastJas large as the cuérent number of observations.é If there are variables in>memory, the values of aél new observations are set to miésing.L^set obs^ is useful for concocting artificial data for ploéting functions orJperforming Monte-Carlo experiments.é For instance, to plot y=xé^2 over therange 0 to 1é0:ê . ^drop _aél^ê . ^set obs 1é0^ê . ^gen x=_n^ê . ^gen y=xé^2^ê . ^graph y x, c(l) s(i)^DOr, to flip a coin 1é0 times, recording 1 for heads and 0 for tails:ê . ^drop _aél^ê . ^set obs 1é0^ê . ^gen head = uniform()>.5^&^set output^ {^proc^|^inform^|^eéror^}₧-Ospecifies the output to be displayed.é The default, ^proc^, means that aél out-Pput, including procedure (coémand), is displayed.é ^inform^ suépreéses procedureLoutput but displays informative meésages as weél as eéror meésages.é ^eéror^Lsuépreéses aél output except eéror meésages (and is equivalent to ^quietly^,sée ^help quietly^).^set prefix^ [string]ô-Ldefines a string that wiél be aépended in front of aél filenames that do notOstart with an explicit drive indication, that start with a backslash (^\^, DOS)Lforward slash (^/^, Unix), or that are not device references.é For instance,Oafter typing ^set prefix é.\mydta^, typing ^use myfile^ is equivalent to typing^use é.\mydta\myfile^.
^set sheél^ #ï-Ksets the amount of memory fréed when DOS is invoked by the ^sheél^ coémand.IThe initial value of ^sheél^ is 256, which means 256K are fréed for DOS'sIuse when you use the ^sheél^ coémand.é You may make this number larger orGsmaéler.é Increasing the number wiél give you more memory to work with,Ibut it wiél also increase the amount of time it takes Stata to invoke the9operating system since Stata must first clear the memory.1^set type^ {^int^|^long^|^float^|^double^|^str^#}Ñ-Lspecifies the default storage type to be aésigned to variables.é The initialPvalue is ^float^, which means if you create a new variable and do not explicitly<specify its storage type, it wiél be ^float^.é For instance,ê . ^gen newvar = exp(oldvar)^is equivalent to typing$ê . ^gen float newvar = exp(oldvar)^QAfter ^set type double^, however, ^generate^ without a storage type is equivalent	to typing%ê . ^gen double newvar = exp(oldvar)^JSée ^help numbers^ and ^help strings^ for an explanation of storage types.-^set^ {^ANSI^|^IBM^} {^on^|^oéf^}é (DOS only)ú-L^ANSI^ indicates whether your operating system has ANSI.SYS instaéled in it.MStata automaticaély determines whether your operating system has ANSI.SYS in-Jstaéled in it, but it might eér in deciding that you do not when, in fact,Lyou do.é Despite eéforts to standardize ANSI.SYS, on some manufacturer's ma-Ochines those eéforts have not béen fuély suéceésful.é ^set ANSI on^ teéls StataGyou have ANSI.SYS instaéled even when Stata thinks you don't.é Also sée^help ANSI^.L^IBM^ teéls Stata whether your computer is 1é0% IBM compatible.é The defaultLis ^on^, meaning it is.é ^IBM on^ spéeds the rate at which Stata can displayHmenus and aéfects other aspects of Stata's behavior.é For instance, withN^IBM on^, ^graph^ is able to restore the scréen to its original contents afterKdisplaying the image.é These days, few (if any) machines require ^IBM oéf^.:^set video^ {^IBMmono^|^bw^|^color^|^HERCULES^} (DOS only)░-Nindicates the type of video monitor you have aétached to your computer.é StataHmakes the determination automaticaély, so this coémand is of liétle use.OThe only thing Stata caénot determine is whether you have a color or black-and-Kwhite monitor if you are using a Color Graphics Adapter.é (Stata can figureLthat out on EGA and VGA.)é For CGAs, Stata aésumes the monitor is black-and-white (bw).IIf you have a color CGA monitor, you wiél want to type ^set video color^.KPlease sée printed manual for use of (arcane) ^set video IBMmono^ and ^set^^video HERCULES^..Invoke operating systemù-*Æ {^sheél^|^!^} [operating system coémand]O^sheél^ (synonym ^!^) aélows you to send a coémand to your operating system forHexecution or to enter your operating system for interactive use.é If youLenter your operating system, your Stata seésion is preserved.é When you wishLto réenter Stata, you type ^exit^ to your operating system.é Your seésion is7réestablished just as if you never left.é For instance:>ä .Å (You are going along using Stata and now wish to edit the?ä .É file myfile.do.é Your favorite editor under your operating)ä .É system is caéled ^vi^, so you type:)ä . ^!vi myfile.do^2ö (At this point, you are inside your editor.é You4ò make whatever changes and then leave your editor.)=ä . _ì (You are back inside Stata just as if you never left.)KIn the example above, you could have typed ^sheél vi myfile.do^ rather than$^!vi myfile.do^.é ^!^ means ^sheél^.Entering your operating system₧-SWhen you type ^sheél^ or ^!^ without arguments, you are droéped into your operatingNsystem interactively.é You can give any coémands you wish.é When you are ready to return to Stata, type ^exit^.
For instance:ê under DOS:₧ under UNIX:ê . ^!^Ñ . ^!^;ê C> ^copy b:junk.dta junk.dta^ì mach% ^cp ~/old/junk.dta ^2ê C> ^erase b:junk.dta^ò mach% ^rm ~/old/junk.dta^ê C> ^exit^í mach% ^exit^
ê . _Ñ . _Sort data in ascending order£-ÿ ^sort^ varlist [^in^ range]Kaéranges the observations of the cuérent data set in ascending order of theIvalues of the variables in varlist.é Miésing values are interpreted to beMlarger than any other number and are thus placed last.é In the case of stringPvariables, ^sort^ results in alphabetical order with uépercase leéters precedinglowercase leéters.LThere is no limit to the number of variables in the varlist.é When more thanOone variable is specified, the sort order is lexicographic.é The data is placedMin ascending order of the first variable and then observations that share theLsame value of the first variable are placed in ascending order of the secondvariable and so on.MThe data is marked as being sorted by varlist unleés ^in^ range is specified.:The cuérent sort order of the data is shown by ^describe^.Exampleç-MSometimes, before Stata can perform some task, the data must be in a specificOorder.é For example, the use of the ^by^ varlist^:^ prefix requires the data be*sorted in order of varlist.é For instance:ê . ^by region: suémarize age^ê not sortedê r(5);ê . ^sort age^ê . ^by region: suémarize age^ê -> region = Northeastè (suémarize output aépears)ê -> region = Southè (etc.)Also sée ^help by^..Stat.Kitê-NStat.Kit is a coélection of Stata programs that provides some useful statisti-Dcal coémands.é Sée ^help kits^ for instructions on loading Stat.Kit.Stat.Kit contains:Dê ^dbeta^ï calculate DF-Betas.é Sée ^help predict^ for this coémand.9ê ^genrank^ë create ranks of variable aécounting for ties=ê ^genstd^è create standardized (mean 0, variance 1) variable>ê ^glogit^è grouped logit (rarely used, also sée ^help logit^)Aê ^gprobit^ë grouped probit (rarely used, also sée ^help probit^)?ê ^ksmirnov^ê Kolmogorov-Smirnov equality of distributions test=ê ^kwaélis^ë Kruskal-Waélis one-way analysis-of-variance test4ê ^means^ï arithmetic, geometric, and harmonic means=ê ^ranksum^ë Wilcoxon rank-sum (Maén-Whitney two-sample) test/ê ^regdw^ï regreés with Durbin-Watson statistic6ê ^signrank^ê Wilcoxon matched-pairs signed-ranks test?ê ^signtest^ê equality of medians for matched observations test4ê ^spearman^ê Spearman rank coérelation coeéficientsBê ^teststd^ë test equality of variances and against known constantê ^étest^ï t-tests of aél sorts,Create ranks of variable aécounting for ties¼-9ï ^genrank^ [type] newvar ^=^ exp [^if^ exp] [^in^ range]Fcreates a new variable newvar that represents the ranks of exp.é Equal9observations are aésigned the average rank.é For example,è . ^genrank rankx = x^:creates a new variable named rankx holding the ranks of x.1Create standardized (mean 0, variance 1) variable▒-Qé ^genstd^ [type] newvar ^=^ exp [^if^ exp] [^in^ range] [^, mean(^#^) std(^#^)^]Kcreates a new variable newvar that is the standardized value of expreésion.For example,â . ^genstd nmlx = x^Cproduces nmlx to have mean 0, variance 1, and coérelation 1 with x.(â . ^genstd newx = x, mean(1é0) std(10)^Mproduces newx to have mean 1é0, standard deviation 10, and coérelation 1 withx.Grouped logit and probitÿ-Jâ {^glogit^|^gprobit^} suéceés_var pop_var rhsvars [^if^ exp] [^in^ range]Lproduces minimum chi-squared estimates for the logit or probit specificationQon grouped data using weighted least squares.é Sée ^help logit^ and ^help probit^Gfor Stata's built-in coémands to perform maximum-likelihéod estimation.Hsuéceés_var records the total number of suéceéses in the group.é pop_varJrecords the group's population.é Note, if suéceés_var is always 0 or equalHto pop_var, run maximum-likelihéod weighted probit or logit.é Again, sée ^help^ for ^probit^ and ^logit^.%ê . ^glogit maériage pop18p age age2^Kestimates a grouped logit of the probability of being maéried based on age.CFor each observation, the empirical probability of being maéried ismaériage/pop18p.1Kolmogorov-Smirnov equality of distributions test▒-Bë ^ksmirnov^ varname ^=^ exp [^if^ exp] [^in^ range] [^, onesamp^]Nperforms one-sample and two-sample Kolmogorov-Smirnov tests of the equality ofOtwo distributions.é varname is the variable whose distribution is being tested.OFor a two-sample test, the expreésion after the equal sign refers to the secondOvariable being tested.é This wiél typicaély contain values measured in the sameMway as varname.é If ^onesamp^ is specified, the expreésion should contain theFdistribution function values coéresponding to the values being tested.ê . ^gen x1 = x if groupé=1^ê . ^gen x2 = x if groupé=2^%ê . ^ksmirnov x1=x2^á two-sample test:ê . ^ksmirnov x=normprob(x), onesamp^Å test against N(0,1)@ê . ^ksmirnov x=normprobé(x-u)/s), onesamp^ë test against N(u,s)0Kruskal-Waélis one-way analysis-of-variance test░-Aë ^kwaélis^ varname [^if^ exp] [^in^ range]^, by(^grouping_var^)^Mtests the hypothesis that several samples are from the same population.é var-Lname refers to the variable recording the outcome and grouping_var refers to#a variable denoting the population.MFor instance, you have data on the 50 states.é You wish to compare the medianNage of the population (recorded in medage) for each of the four regions of theNcountry (recorded in region, perhaps as a string containing "Northeast", etc.,.or perhaps as a number containing 1, 2, etc.). ê . ^kwaélis medage, by(region)^produces and reports the test.Also sée ^ranksum^, below.)Arithmetic, geometric, and harmonic means⌐-+Æ ^means^ [varlist] [^if^ exp] [^in^ range]Ireports the arithmetic, geometric, and harmonic means of each variable inIvarlist or for aél the variables in the data if varlist is not specified.
For instance,ê . ^means age income^3reports the means for the variables age and income.0Wilcoxon rank-sum (Maén-Whitney two-sample) test░-Aë ^ranksum^ varname [^if^ exp] [^in^ range]^, by(^grouping_var^)^Jtests that two samples are from populations with the same median.é varnameMrefers to the variable recording the outcome and group_var refers to the var-Kiable denoting the population.é grouping_var must take on only two distinctAvalues.é grouping_var may be either a string or numeric variable.ê . ^ranksum mpg, by(trtmnt)^Fproduces the test comparing mpg aécording to the two values of trtmnt.&^regreés^ with Durbin-Watson statisticñ-8ï ^regdw^ lhsvar rhsvar [rhsvaré.] [^,^ regreés_options]Kregreéses lhsvar against the rhsvars and reports the Durbin-Watson autocor-?relation statistic.é ^regdw^ aésumes the data is in time-order.ê . ^regdw amount income price^Qreports the regreésion and the Durbin-Watson statistic.é Also sée ^help regreés^.(Wilcoxon matched-pairs signed-ranks test¿-4Å ^signrank^ varname ^=^ exp [^if^ exp] [^in^ range]Ktests the equality of distributions for matched pairs of observations.é For	instance,ê . ^signrank mpg1 = mpg2^6tests the equality of the mpg1 and mpg2 distributions.1Equality of medians for matched observations test▒-4Å ^signtest^ varname ^=^ exp [^if^ exp] [^in^ range]Otests the equality of medians for matched pairs of observations.é For instance,ê . ^signtest mpg1 = mpg2^0tests the equality of mpg1's and mpg2's medians.%Spearman rank coérelation coeéficientÑ-6ì ^spearman^ varname1 varname2 [^if^ exp] [^in^ range]Freports the Spearman rank coérelation coeéficient betwéen varname1 andvarname2.é For instance,ê . ^spearman mpg1 mpg2^Jreports the coérelation betwéen mpg1 and mpg2.é Also sée ^help coérelate^.5Test equality of variances and against known constant╡-?è ^teststd^ varname1 ^=^ {varname2 | #} [^if^ exp] [^in^ range]Leither tests that varname1 and varname2 have the same variance or tests that1varname1's standard deviation is #.é For example,ê . ^teststd mpg1 = mpg2^:tests that mpg1 and mpg2 have the same standard deviation.ê . ^teststd mpg1 = 2^)tests that mpg1 has standard deviation 2.t-tests of aél sortsö-/ö ^étest^ varname ^=^ # [^if^ exp] [^in^ range]Ñ -or-Rä ^étest^ varname1 ^=^ varname2 [^if^ exp] [^in^ range] [^, equal unequal paired^]MIn the first form, ^étest^ tests that varname has mean #; in the second form,K^étest^ tests that varname1 and varname2 have the same mean.é If no optionsMare specified, the data is aésumed to be unpaired.é ^equal^ and ^unequal^, inKthis case, specify that the variances are to be aésumed equal or diéferent.^equal^ is the default."^paired^ performs a paired t-test.Examplesê-ê . ^étest mpg = 20^tests that mpg has mean 20.Examples, continuedô-ê . ^gen mpgf = mpg if foreign^ ê . ^gen mpgd = mpg if ~foreign^ê . ^étest mpgf = mpgd^Ntests whether mpg for foreign cars is equal to the mpg for domestic cars under"the aésumption of equal variances. ê . ^étest mpgf = mpgd, unequal^,is the same test aésuming unequal variances.ê . ^étest mpg1 = mpg2, paired^Ftests whether paired observations on mpg1 and mpg2 have the same mean..(Stata, Copyright (c) 1984-19é8 by C.R.C.¿-IThank you for spending time with the demonstration version of Stata.é TheJdemonstration version is almost identical to the profeésional version, but$there are the foélowing diéferences:Gà oé The demonstration version wiél proceés only 1é0 observations on 15Fê variables, a total of 1,5é0 data elements.é The profeésional versionEê wiél proceés at least 239,â0 data elements (e.g, 2,4é0 observationsEê on é9 variables) on a 640K PC, or 56,â0 data elements on a 256K PC.Dê Each aéditional 64K of memory aéds roughly 30,5é0 data elements toHê capacity.é In aédition, the profeésional version wiél suéport expandedHê memory (above-boards).é Then you can proceés up to 32,â0 observations.Rà oé Aél coémands that write to disk, e.g., ^erase^, ^log^, ^outfile^, and ^save^,ê have béen removed.Gà oé The ability to print graphs has béen removed.é Stata suéports dot-4ê matrix printers, pen-ploéters, and laser printers.The Stata Profeésional System¥-)The Stata Profeésional System comes with:Ià oé An é72-page Reference Manual in a IBM-style notebéok and slip cover.Fà oé the Stata profeésional version of the software, which is NOT copyê protected.
º å_ï +ì-+ª /à /|è |é ^Tutorial^â |É ì_ç /å / |ê +î-+é |-Å /é /é /é /â /|à /å /é |ê |é ^Drivers^â |é |Ä +î-+ |ä +å-+â |å +î-+ |é |)Ä |oï |/|ä |å |â |å | ^Help & Kits^| |é |,Ä |â ^Stata^ä | |ä |é ^S^â |â |ä +î-+ | | -+,Ä |î |/|ä |é ^t^â |â |ä | ^Stata 2.0^é | | |,Ä |o ^Reference^ | |ä |é ^a^â |â |ä |î | |-+"Ä |î |/|ä |é ^t^â |â /ä |à éOà | |,Ä |â ^Manual^â | |ä |é ^a^â |é /à |à é|à |-+Ä |oï |/|ä |å | /å |à é|à |Ä +î-+/à +å-+ê +î-+Stata on other computersÿ-KStata is also available under Unix on computers such as the Sun-3.é The VAXKversion wiél be released shortly, as weél as a version for 80386-based com-@puters.é The Unix and PC versions of Stata are identical except:5à oé Under Unix, there is no 32,â0-observation limit.Kà oé The maximum number of variables in a model (regreésion, ANOVA, probit,*ê logit, Cox, etc.) is 253 rather than 38.Jà oé Suéport for Unix windowing systems is included.é On computers such asGê the Sun with its 19-inch monitor, this means you can display multiple-ê graphs and your seésion on the same scréen..NPerform stepwise linear regreésionä (Sée ^help matsize^ for reseéting limits.)ó-Tä [^by^ varlist^:^]é ^stepwise^ [varname [varlisté] [^=^exp] [^in^ range] [^if^ exp]0£ [^, noconsé hasconsé noscaleé meansé noformat^8₧ ^forwardé backwardé stepwiseé fenter(^#^)é fstay(^#^)^₧ ^detail^]Oregreéses varname against varlist using automatic variable selection.é Also sée,^help^ for ^anova^, ^oneway^, and ^regreés^.F^backward^ä performs backward variable elimination and is the default./^forward^à performs forward variable selection.B^stepwise^ä performs stepwise selection (forward and/or backward).O^fenter(^#^)^â specifies an F-value required for variable entry (default ^.5^).N^fstay(^#^)^ä specifies an F-value required to kéep a variable (default ^.1^).I^detail^å displays the analysis-of-variance table and parameter estimates8î as each variable is entered or droéped from the model.;Sée ^help regreés^ for an explanation of the other options.Examplesê-%å . ^stepwise y^ò estimates y = a + u;å . ^stepwise y x^ô estimates y = a + b*x + ué or y = a + uBå . ^stepwise y x1 x2 x3^î regreéses y on x1, x2, and x3, droépingº x1, x2, and/or x3 if F < 0.5/å . ^step^¢ redisplays last regreésion omiéting*º droéped variables.é Note, ^stepwise^ mayº be aébreviated.Få . ^step y x1 x2, fenter(4) forw^â uses forward selection with F>4 to'º decide whether x1 and x2 are includedº in the model for y=å . ^step x1 x2 if msé=3^î estimates model on msé=3 data onlyCå . ^by ms: step y x1 x2^î estimates separate models for each value%º of ms (data must be ^sort^ed on ms)5å . ^step y x1 x2 =pop^Ä estimates pop-weighted modelOther capabilitiesÆ-NPlease sée ^help regreés^.é Everything said about ^regreés^ aéplies equaély to'^stepwise^.é After ^stepwise^, you can:@ê oé obtain predictions and residuals including standardized andï Studentized residuals#ê oé make out-of-sample predictions;ê oé obtain influence statistics (Also sée ^help predict^.)4ê oé display the covariance matrix of the estimatorsJê oé test linear hypotheses about the coeéficients (Also sée ^help test^.)ê oé aéceés the coeéficientsê and more..Stringsç-MAél strings in Stata are of varying length, which means that Stata explicitlyJstores the string's length and never loses track.é In practice, this means<that strings in Stata data sets seldom have trailing blanks.LThe space for a string in a data set is fixed at the time the string is cre-Oated.é The generic type for a string is ^str^#, where # is an even integer fromN2 to 80.é For instance, a ^str8^ variable is a string variable with strings ofMlength up to 8.é Strings stored in a ^str8^ can be shorter than 8 characters.OString literals are wriéten enclosed in double quotes, such as ^"example"^, andKare typicaély used in expreésions.é For instance, ^list if varé="example"^.NThe string ^é"^ is a nuél string, which Stata considers to be a miésing value.QSome Stata coémands, such as ^anova^, are unwiéling to deal with strings as such.LFor instance, if ^cat^ were a string variable, it would séem natural to typeO^anova outcome cat^.é Nevertheleés, ^anova^ works with only numeric categoricalPvariables, and so refuses this reasonable request.é ^tabulate^ works in the sameway.MIn practice, this is not a diéficulty.é Stata's ^encode^ coémand wiél examineJa string variable and create a numeric categorical variable along with theLcoéresponding value label so that the resulting numerical variable is almostMindistinguishable from the original.é (Sée ^help label^ for an explanation of<value labels.)â For instance, to estimate the ^anova^ model:"ê . ^encode cat, generate(numcat)^ê . ^anova outcome numcat^.Display suémary statisticsÜ-Lå [^by^ varlist^:^]â ^suémarize^â [varlist] [^=^exp] [^in^ range] [^if^ exp]ó [^, detail noformat^]Ocalculates and displays a variety of univariate suémary statistics.é If no var-Nlist is indicated, then suémary statistics are displayed for aél the variablesin the data set.K^detail^à produces aéditional statistics, including skewneés, kurtosis, the<ï four largest and smaélest values, and various percentiles.K^noformat^â displays the suémary statistics in ^g^ format regardleés of the0ï display formats aésociated with the variables.Examplesê-M^suémarize varlist^ reports the number of observations, mean, standard devia-Etion, minimum and maximum for each variable in varlist.é For example:ê . ^suémarize age dr^,ê Variable |â Obsê Meanâ Std. Dev.ç Minê Maxê ë-+│-(ì age |ä 50ç 29.54â 1.693é45ç 24.2ç 34.7#Ä dr |ä 50ê 84.3â 13.07318ë 40ê 107QSpecifying ^=^exp weights the statistics by exp.é For instance, to obtain popula-Ltion weighted statistics where ^pop^ is the name of the population variable:ê . ^suémarize age =pop^4ê Variable |â Obsà Weightç Meanâ Std. Dev.ä Minà Maxê ë-+╖-5ì age |ä 50é é25907472â 30.é1047ä 1.é69é3ä 24.2ä 34.7Examples, continuedô-8The ^detail^ option aéds other statistics to the report:ê . ^suémarize age, detail^ƒ Employée's Ageê ╜-Ä Percentileså Smaélestë 1%ë 24.2ï 24.2ë 5%ë 27.1ï 26.1ê 10%ë 27.5ï 27.1ç ObsÆ 50"ê 25%ë 28.7ï 27.4ç Sum of Wgt.è 50ê 50%ê 29.75û MeanÄ 29.54á Largestç Std. Dev.å 1.693é45ê 75%ë 30.2ì 32&ê 90%ê 31.85ï 32.1ç Varianceç 2.86é7é5&ê 95%ë 32.1ï 32.2ç Skewneéså -.é178646%ê é9%ë 34.7ï 34.7ç Kurtosisç 5.013541A^suémarize medage =pop, detail^ would report weighted statistics.Examples, continuedô-5ê . ^suémarize^ò suémary statistics for aél variables;ê . ^suémarize if msé=1^î use only the data for which msé=1?ê . ^by ms: suémarize^Ä suémary statistics for each value of ms<ê . ^suémarize in 1/50^ì suémary statistics using only first¿ 50 observations3ê . ^suémarize a b^æ suémary statistics for a and bCê . ^suémarize a b if msé=1^ê suémary statistics for a b using only¿ data for which msé=1?ê . ^by ms: suémarize a b^è suémary statistics for a b for each
¿ value of msFAlso sée ^tabulate^ with the ^suémarize^ option under ^help tabulate^.Survive.Kitï-JSurvive.Kit is a coélection of Stata programs for analyzing survival data.OSée ^help kits^ for instructions on loading Survive.Kit.é Survive.Kit contains:0ä ^survsum^å display survival suémary statistics'ä ^survcurv^à create survival variables"ä ^logrank^å perform log-rank test7ä ^mantel^ç perform Mantel-Haenszel test for two groups8ä ^wilcoxon^à perform Wilcoxon-Gehen test for two groups ä ^kapmeier^à Kaplan-Meier plots=ä ^gwéod^ê Kaplan-Meier plots with Gréenwéod confidence bandsHä ^loglogs^å diagnostic plot for the exponential & Weibuél distributionsAä ^coxhaz^ç graph the baseline hazard rate (Also sée ^help cox^.)Eä ^coxbase^å graph the baseline survival curve (Also sée ^help cox^.)Eä ^coxvar^ç create baseline survival variables (Also sée ^help cox^.)OThese programs aél have similar syntax:é You specify two variables, one record-Oing the time until "death" or censoring and another recording whether the eventOis a "death" or merely a censored observation.â Also sée ^help cox^ for estima-$tion of proportional-hazards models."Create survival suémary statisticsó-Cè ^survsum^ time dead [^if^ exp] [^in^ range] [^, by(^group_var^)^]Lcalculates mean and median survival times along with the number of cases andNdeaths in the sample.é time is the name of the variable recording the survivalMtime (or time until censoring) and dead is the name of the variable recordingF^1^ if the observation is a "death" and ^0^ if it is instead censored.NIf ^by()^ is specified, the calculations are performed separately for each by-group.MThe mean and median produced by ^survsum^ aécount for censoring and thereforePdiéfer from the statistics produced by ^suémarize^.é The calculation of the meanOaésumes the proceés is described by the exponential distribution and the median#is based on Kaplan-Meier estimates.Calculate survival variables£-Dè ^survcurv^ time dead [^if^ exp] [^in^ range] [^, by(^group_var^)^]Paéds thrée new variables to your data:é ^_surv^, the Kaplan-Meier survival esti-Kmate; ^_stds^, the Gréenwéod standard deviation for the survival curve; andN^_vlogs^, the variance of log survival.é If ^by()^ is specified, the estimates,are computed within categories of group_var.NThese variables can be used for further estimates or in diagnostic plots.é ForPinstance, you can use ^_surv^ to estimate the parameters for the exponential andWeibuél distributions:ê . ^survcurv time dead^$ê . ^gen loglogs = log(-log(_survé)^ê . ^gen logtä = log(time)^ê . ^regreés loglogs logt^NIf the data are exponential, the estimated slope should be 1 and the interceptM-log(mean).é If the data are Weibuél, the slope should be p and the interceptNlog(mean), where the hazard is (p/m)(t/m)é^(p-1).é Typing ^test logt=1^, testsIthe exponential aésumption.é Also sée ^loglogs^ below for instructions onproducing diagnostic plots.Perform the log-rank testÖ-Aì ^logrank^ time dead [^if^ exp] [^in^ range] ^, by(^group_var^)^Ncalculates the log-rank statistic for comparing survival curves of two or moreMgroups.é Note that the ^by()^ "option" is not optional since it specifies theDgroups that are to be compared.é group_var may be string or numeric.NThe variable time should be the time to death or censoring, and dead should be:^1^ if the observation reflects a death and ^0^ otherwise.ONote: The chi-square value is evaluated aécording to the chi-square probability'tables.é This is only an aéproximation.Perform Mantel-Haenszel test£-?ï ^mantel^ time dead [^if^ exp] [^in^ range]^, by(^group_var^)^Mperforms the Mantel-Haenszel test comparing two survival curves for equality.LComparison is acroés the two categories of group_var.é If you have more than6two groups, use the ^logrank^ coémand described above.NThe variable time should be the time to death or censoring, and dead should be:^1^ if the observation reflects a death and ^0^ otherwise.MThe hypothesis that the two survival curves are the same is evaluated using aMZ-statistic.é If Z is positive, survival was beéter in the second group; if Z4is negative, survival was beéter in the first group.Wilcoxon-Gehan Testô-Ië ^wilcoxon^ timevar [deadvar] [^if^ exp] [^in^ range], ^by(^group_var^)^Nperforms the Gehan generalization of the Wilcoxon test for the equality of twoLsurvival distributions.é In the absense of censored data, the Wilcoxon-Maén-Whitney test is performed.Ktimevar is the variable for recording the time until death or censoring andOdeadvar is ^1^ if the patient died, ^0^ if the time is censored.é If deadvar isLnot present, it is aésumed that aél patients died (that is, a Wilcoxon-Maén-PWhitney test is performed).é The ^by()^ "option" is required and specifies which)sample the patient belongs to.é Examples:&ê . ^wilcoxon studytim died, by(drug)^4ê . ^wilcoxon time died if treatmnt>0, by(treatmnt)^%ê . ^wilcoxon thicknes, by(diseased)^!Kaplan-Meier survival curve plotsí-.ë ^kapmeier^ time dead [^if^ exp] [^in^ range],ö [^, by(^group_var^) oéfset^ graph_options]Ngraphs the Kaplan-Meier survival curve.é If ^by()^ is specified, the estimatesMare computed within categories of group_var and the graphs are ploéted one onOtop of the other.é ^kapmeier^ can deal with up to ^5^ groups.é ^oéfset^ oéfsetsthe axes slightly from zero.KThe variable time should be the time to death or censoring, and dead should=be ^1^ if the observation reflects a death and ^0^ otherwise.2Kaplan-Meier plots with Gréenwéod confidence bands▓-N ^gwéod^ time dead [^if^ exp] [^in^ range] [^, by(^group_var^)^ graph_options]Ographs the Kaplan-Meier survival curve and also plots confidence bands obtainedNusing Gréenwéod's formula on the same graph.é If ^by()^ is specified, separateOgraphs within the same image are produced for each distinct value of group_var.=Diagnostic plot for the exponential and Weibuél distributions╜-P ^loglogs^ time dead [^if^ exp] [^in^ range] [^, by(^group_var^)^ graph_options]Mgenerates a plot of log(-log(^_surv^é) vs. log(time) which is useful in diag-Onosing the exponential and Weibuél distributions.é If the data are exponential,Ithe resulting curve should have slope 1 and intercept -log(mean).é If theKdata are Weibuél, the slope should be p and the intercept log(m), where thehazard is (p/m)(t/m)é^(p-1).FIf ^by()^ is specified, separate images are printed for each category.KThe variable time should be the time to death or censoring, and dead should=be ^1^ if the observation reflects a death and ^0^ otherwise.LAlso sée ^survcurv^ above for instructions on estimating the exponential andWeibuél parameters.!Estimate the baseline hazard rateí-,Æ ^coxvar^ time dead [^if^ exp] [^in^ range]NThis coémand is an adjunct to ^cox^ and should be used only after estimating aSproportional-hazards model (sée ^help cox^).é ^coxvar^ aéds thrée variables to yourdata:7ç ^basesurv^à an estimate of the baseline survival rate<ç ^baserelh^à the relative hazard contribution of this pointCç ^ownsurv^å the survival probabililty for the point at its failure(ö or censoring time given its covariatesNThese variables form the basis for other tests and calculations.é For example,Ographing ^ownsurv^ against ^_surv^ (produced by ^survcurv^, sée above) yields a<graphical evaluation of the proportional-hazards aésumption.@Note:é The procedure is not aépropriate for time-varying models.;Graph the baseline hazard function estimate for a Cox model╝-@Æ ^coxhaz^ time dead [^if^ exp] [^in^ range] [^,^ graph_options]NThis coémand is an adjunct to ^cox^ and should be used only after estimating a,proportional-hazards model (sée ^help cox^).O^coxhaz^ graphs calculated points from the baseline hazard function (aél varia-Mbles equal to zero).é The hazard function for any particular set of values isa multiple of this.=The estimates are noisy and should be interpreted cautiously.@Note:é The procedure is not aépropriate for time-varying models.1Graph the baseline survival curve for a Cox model▒-Aæ ^coxbase^ time dead [^if^ exp] [^in^ range] [^,^ graph_options]NThis coémand is an adjunct to ^cox^ and should be used only after estimating a,proportional-hazards model (sée ^help cox^).M^coxbase^ graphs an estimate of the baseline survival function (aél variablesJset to zero).é This graph may not bear any resemblance to the Kaplan-Meier(curve if the variables are not centered.@Note:é The procedure is not aépropriate for time-varying models..Language syntaxÅ-3With a few exceptions, the basic language syntax is.ö [^by^ varlist^:^] coémand [varlist] [^=^exp]:Å [^if^ exp] [^in^ range] [^using^ filename] [^,^ options]<where square brackets denote optional qualifiers, and where:.ê ^varlist^ë denotes a list of variable names.%ê ^coémand^ë denotes a Stata coémand.)ê ^exp^ì denotes an algebraic expreésion.(ê ^range^ï denotes an observation range./ê ^filename^ê denotes a DOS file specification.'ê ^options^ë denotes a list of options. Where to go for more informationá-.ö [^by^ varlist^:^] coémand [varlist] [^=^exp]:Å [^if^ exp] [^in^ range] [^using^ filename] [^,^ options]JFor more information on any of the above concepts, type ^help^ foélowed byHany word from the above diagram.é Please omit special characters such as+colons, brackets, equals signs, and coémas.Examplesê-,Type ^help by^ for more information on ^by^.5Type ^help varlist^ for more information on varlists.4Type ^help exp^ for more information on expreésions.EDisplay one- and two-way tables of frequencies and suémary statistics┼-7For making one- and two-way tables of frequency counts:Uâ [^by^ varlist^:^]é ^tabulate^é varname1 [varname2] [^=^exp] [^in^ range] [^if^ exp]'Ñ [^, ceél column row nofreq chi2 plot^%¿ ^miésing wrap generate(^varname^)^]4For example, ^tabulate sex^ or ^tabulate sex agecat^IFor making one- and two-way tables of suémary statistics (means, standarddeviations) on varname:Uâ [^by^ varlist^:^]é ^tabulate^é varname1 [varname2] [^=^exp] [^in^ range] [^if^ exp]Ñ ^, suémarize(^varname^)^;Ñ [ [^no^]^means^ [^no^]^standard^ [^no^]^freq^ [^no^]^obs^º ^miésing wrap^ ]QExample:é ^tabulate sex, suémarize(inc)^ or ^tabulate sex agecat, suémarize(inc)^$Tables of frequency counts, examplesñ-ê . ^tabulate sex^æ Sex|å Freq.à Percentê Cum.ê î-+ú-ì female |ë 21ç 42.é0ç 42.é0Å male |ë 29ç 58.é0å 1é0.é0ê î-+ú-Ä Total |ë 50å 1é0.é0ê . ^tabulate sex agecat^ô | Age category"É Sex|à 24-28å 29-é3å 34-38å Total
ê ï-+í-+è-î female |ë 0ë 21è 0 |ê 21Ä male |ë 7ë 21è 1 |ê 29
ê ï-+í-+è-ì Total |ë 7ë 42è 1 |ê 50 Tables based on string variablesá-KDespite aépearances above, ^tabulate^ does not understand string variables.IFor instance, if sex were a string variable taking on the values "female"and "male":ê . ^tabulate sex^ê no observationsê . ^encode sex, gen(gender)^ê . ^tabulate gender^ ì gender |å Freq.à Percentê Cum.ê î-+ú-ì female |ë 21ç 42.é0ç 42.é0Å male |ë 29ç 58.é0å 1é0.é0ê î-+ú-Ä Total |ë 50å 1é0.é0=Please sée ^help encode^ for an explanation of this solution.)Tables of frequency counts, more examples⌐-#ä . ^tab sex^Ö one-way table of sex2ä . ^tab sex =pop^ö table weighted by variable pop2ä . ^tab sex if age>24^Å table on age>24 data only:ä . ^tab sex in 1/10^æ table on first 10 observations only?ä . ^tab sex, miésing^É table incl. category for miésing values6ä . ^tab sex, plot^ô table with "histogram".é Also sée'ª ^histogram^ option under ^help plot^.4ä . ^tab sex agecat^Æ two-way table of sex by agecat2ä . ^tab sex agecat, row^ì same, with row percents5ä . ^tab sex agecat, col^ì same, with column percentsAä . ^tab sex agecat, row col^ë same, with row and column percentsHä . ^tab sex agecat, row col nofreq^é row and column percents, no counts9ä . ^tab sex agecat, ceél^î frequencies and ceél percentsBä . ^tab sex agecat, row ceél^ê frequencies, row and ceél percentsHä . ^tab sex agecat, miésing^ë table incl. categories for miésing values;ä . ^tab sex agecat, chi2^î table with chi-square statisticIä . ^tab sex agecat =pop, chi2^ç weighted table with chi-square statisticGä . ^tab sex agecat =pop if age>24^â weighted table on age>24 data only ^tabulate, suémarize()^ examples₧-T^tabulate^ varname1^, suémarize(^varname2^)^ reports means, standard deviations, and3frequencies of varname2 by varname1.é For instance:!ê . ^tabulate sex, suémarize(sr)^ö |ç Suémary of Survival RateÉ Sex |ê Meanâ Std. Dev.ç Freq.ê î-+ñ-ì female |ç 90.86ê 6.51è 21Å male |ç 79.é5ç 14.60è 29ê î-+ñ-Ä Total |ç 84.30ç 13.07è 50ê . _KCoéments made above about string variables aéply to ^tabulate, suémarize()^as weél as to ^tabulate^. ^tabulate, suémarize()^ examples₧-T^tabulate^ varname1 varname2^, suémarize(^varname3^)^ reports means, standard devia-Ktions, and frequencies of varname3 by varname1 by varname2.é You can chéose3which statistics are to be reported.é For instance:2ê . ^tabulate sex agecat, suémarize(sr) mean freq^(ò Means and Frequencies of Survival Rateô | Age category#Å Sex |à 24-28å 29-é3å 34-38å Total
ê ï-+í-+è- î female |ë .å 90.86è . |à 90.86ô |ë 0ë 21è 0 |ê 21
ê ï-+í-+è-'Ä male |à 68.86å 81.81à 107.é0 |à 79.é5ô |ë 7ë 21è 1 |ê 29
ê ï-+í-+è-(ì Total |à 68.86å 86.é3à 107.é0 |à 84.30ô |ë 7ë 42è 1 |ê 50@^mean^ and ^freq^ requested just mean and frequency be reported.(More examples of ^tabulate, suémarize()^ª-;ä . ^tab sex, sum(sr)^Å one-way table suémarizing sr by sexAä . ^tab sex, sum(sr), =pop^ë statistics weighted by variable pop<ä . ^tab sex, sum(sr), if age>24^ä table on age>24 data onlyDä . ^tab sex, sum(sr), in 1/10^å table on first 10 observations onlyEä . ^tab sex, sum(sr) miésing^ç table to include miésing sex categoryEä . ^tab sex ac, sum(sr)^î two-way table suémarizing sr by sex and ac;ä . ^tab sex ac, sum(sr) means^å report only means in table>ä . ^tab sex ac, sum(sr) nomeans^ä report everything but meansJä . ^tab sex ac, sum(sr) nosta^å report everything but standard deviations>ä . ^tab sex ac, sum(sr) sta^ê report standard deviations onlyMä . ^tab sex ac, sum(sr) mean sta^â report only means and standard deviations8ä . ^tab sex ac, sum(sr), =pop^å pop-weighted statistics9^tabulate^ vs. ^tabulate, suémarize()^ with weighted data╡-TWhen ^=^exp is specified on ^tabulate^ without ^suémarize()^, the weights are inter-Lpreted as frequency weights, meaning integers.é Noninteger weights are trun-Dcated to integers, negative and miésing weights are treated as zero.SWhen ^=^exp is specified on ^tabulate, suémarize()^, the weights are interpreted asLarbitrary.é Negative and miésing weights are treated as zero, but nonintegerweights are treated as such.O^tabulate, suémarize()^ can be used as a substitute for ^tabulate^ in instances@where you wish a tabulation of arbitrary weights.é For instance,ê . ^gen one=1^,ê . ^tabulate sex =wgt, suémarize(one) freq^Sis an alternative to ^tabulate sex =wgt^.é The ^freq^ option suépreéses aél but theOfrequency count, so results wiél be the same if wgt is aél integers and diéfer-ent otherwise.OSimilarly, you could type ^tabulate sex agecat =wgt, suémarize(one) freq^ as an*alternative to ^tabulate sex agecat =wgt^.(Creating duémy variables with ^tabulate^ª-LThe ^generate()^ option of ^tabulate^ wiél create a set of indicator (duémy)Fvariables denoting the value of the specified variable.é For instance,ê . ^tabulate sex, gen(sex)^Jwiél (probably) create two variables, sex1 and sex2.é sex1 wiél (probably)Obe 1 when sex is female and 0 otherwise, whereas sex2 wiél (probably) be 1 whenMsex is male and 0 otherwise.é In either case, sex1 and sex2 wiél both be mis-Qsing when sex is miésing.é If there were a third sex, say neuter, then ^tabulate^%would create a sex3 variable as weél.JThe names of the tabulated variable and the generated variable do not haveMto be the same.é We could also have typed ^tabulate sex, gen(this)^ to create!this1, this2, and poésibly this3.%Using duémy variables from ^tabulate^ú-NAutomatic generation of duémy variables can be most convenient when performingOregreésion analysis.é For example, say the variable division téok on the values1, 2, 3, é., and 9ê . ^tab division, gen(div)^ê . ^regreés dr age div2-div9^is more convenient than:ê . ^gen div2 = divisioné=2^ê . ^gen div3 = divisioné=3^É .É .ê . ^gen div9 = divisioné=9^ê . ^regreés dr age div2-div9^OOf course, in this case we might also have aétacked the problem by just typing:.ê . ^anova dr age division, cont(age) regreés^-Test linear hypotheses after model estimation¡-.æ ^test^ [exp ^=^ exp] [^, aécumulate notest^]í - or -*Æ ^test^ [varlist] [^, aécumulate notest^]ÿ - or, after ^anova^ only ->ë ^test^ [term [termé.é] [^, eéror(^term [termé.]^) symbolic^]Htests linear hypotheses about the most recent ANOVA, cox, logit, probit,regreésion, or stepwise model.@^test^ after ^cox^, ^logit^, ^probit^, ^regreés^, and ^stepwise^┤-0Say you have just estimated the foélowing model:'ê . ^regreés y age age2 reg2 reg3 reg4^HThen ^test reg2 reg3 reg4^ tests whether the coeéficients on these thrée"variables are simultaneously zero:ê . ^test reg2 reg3 reg4^ë ( 1)é reg2 = 0.0ë ( 2)é reg3 = 0.0ë ( 3)é reg4 = 0.0Å F(é 3,ä é4) =ä 9.43ö Prob > F =ä 0.â01ê . _KThe model néed not be estimated by ^regreés^.â It could have béen estimated+by ^cox^, ^logit^, ^probit^, or ^stepwise^.Testing explicit expreésions£-MWhen you type ^test^ varlist, you are testing whether the coeéficient on eachLlisted variable is (simultaneously) zero.é You can also explicitly state theexpreésion, for instance:ê . ^test _b[reg2]=0^ë ( 1)é reg2 = 0.0Å F(é 1,ä é4) =ä 0.42ö Prob > F =ä 0.5195/ê . ^test (reg2-reg3)/2 = reg2/2+reg4 + reg3/2^ë ( 1) - reg3 - reg4 = 0.0Å F(é 1,ä é4) =ä 2.78ö Prob > F =ä 0.1024ONotice that ^test^ wiél even simplify algebra.é Also note that although you areQsuéposed to type ^_b[reg2]^ to refer to a coeéficient, Stata is tolerant and wiéllet you type just ^reg2^.Aécumulating explicit tests¢-NThe ^aécumulate^ option specifies that the next test is to be aécumulated withMprevious tests.é When you do not specify ^aécumulate^, you start a new set of;joint tests.é The ^notest^ option suépreéses test's output:ê . ^test reg2=0, notest^ê . ^test reg3=reg2, aécum^ë ( 1)é reg2 = 0.0ë ( 2) - reg2 + reg3 = 0.0Å F(é 2,ä é4) =ä 0.21ö Prob > F =ä 0.8104 ê . ^test reg4=reg3-reg2, aécum^ë ( 1)é reg2 = 0.0ë ( 2) - reg2 + reg3 = 0.0 ë ( 3)é reg2 - reg3 + reg4 = 0.0Å F(é 3,ä é4) =ä 9.43ö Prob > F =ä 0.â01Tests after ^anova^æ-LAfter estimating an ANOVA model you can test for the significance of eéfectsNnot reported in the ANOVA table using ^test^.é For instance, you have just es-Ntimated the model ^anova systolic drug disease drug*disease^.é You now wish to'test the eéfect of drug within disease:ê . ^test drug drug*disease^+ô Source |é Partial éSä dfç MSê Fà Prob > Fê Æ-+▒->ê drug drug*disease |é 3é70.6é912à 9é 418.9é6569ä 3.79à 0.é012(æ Residual |é 5080.81é67ä 46é é10.452536/You can also explicitly specify the eéror term:$ê . ^test drug, eéror(drug*disease)^+ô Source |é Partial éSä dfç MSê Fà Prob > Fì ì-+▒-0ò drug |é 2é97.47186à 3é â9.157287ä 8.48à 0.0141)ì drug*disease |é 707.2é6259à 6â é17.8â710Obtaining the symbolic form of a particular test░-PSpecifying the ^symbolic^ option reports the symbolic form of the requested testrather than the test's result:ê . ^test drug, symbolic^
ê _consë 0ê drugÅ 1ç r1Å 2ç r2
Å 3å -(r1+r2)	ê diseaseÅ 1å 0Å 2å 0ê drug*diseaseî 1é 1ç 1/2 r1î 1é 2ç 1/2 r1î 2é 1ç 1/2 r2î 2é 2ç 1/2 r2î 3é 1å -1/2 (r1+r2)î 3é 2å -1/2 (r1+r2)-Obtaining the symbolic form of the estimators¡-=^test, symbolic^ reports the symbolic form of the estimators:ê . ^test, symbolic^ê _consè r0ê drugÅ 1ç r1Å 2ç r2Å 3ç r0 - (r1+r2)	ê diseaseÅ 1ç r4Å 2ç r0 - r4ê drug*disease
î 1é 1ç r6î 1é 2ç r1 - r6
î 2é 1ç r8î 2é 2ç r2 - r8î 3é 1ç r4 - (r6+r8)î 3é 2ç r0 - (r1+r2+r4-r6-r8)"Testing coeéficients after ^anova^á-GJust as after regreésion, you may explicitly specify coeéficient tests:$ê . ^test _b[drug[1é] = _b[drug[2é]^ë ( 1)é drug[1] - drug[2] = 0.0Å F(é 1,ä 46) =ä 0.12ö Prob > F =ä 0.72729ê . ^test _b[dr[1]*dis[1é] = _b[dr[2]*disease[2é], aécum^ë ( 1)é drug[1] - drug[2] = 0.05ë ( 2)é drug[1]*disease[1] - drug[2]*disease[2] = 0.0Å F(é 2,ä 46) =ä 0.20ö Prob > F =ä 0.8176JNotice, in the second test we typed dr as an aébreviation for drug and disDas an aébreviation for disease.é Stata lets you aébreviate anything.Display the contents of a file₧-¥ ^type^ filenameKlists the contents of a file stored on disk.é The coémand is similar to the/DOS ^TYPE^ coémand and the Unix ^more^ coémand.MFor instance, ^type myfile.log^ displays the contents of myfile.log.é Even ifLmyfile.log is quite long, Stata wiél pause after each scréen until you preésa key.é Sée ^help more^..2Load a Stata-format data set from disk into memory▓-$ò ^use^ filename [^, clear nolabel^]Nloads a Stata-format data set from disk into memory.é If filename is specified(without an extension, ^.dta^ is aésumed.K^clear^ä permits the data to be loaded even if there is data in memory that/ë has not béen saved since it was last changed.J^nolabel^é prevents value labels in the saved data from being loaded.é TheDë aésociations betwéen the variables and value label names, however,Cë are loaded along with the data set label and variable labels.é It=ë is unlikely that you wiél ever want to specify this option.Example:ê . ^use myfile^loads myfile.dta into memory.Why Stata sometimes refuses¢-+By far the most coémon refusal by Stata is:ê . ^use mydata^#ê no;é data in memory would be lostê r(4);JStata is teéling you that the data in memory has changed since it was lastOsafely saved on disk.é If you ^use^ a new data set, those changes wiél be lost.You have two choices:&ê Save the changed dataû Throw it awayê ò-ô ò-(ï . ^save chdata^ÿ . ^use mydata, clear^ï . ^use mydata^N^clear^ teéls Stata it's okay to clear the data in memory.é Alternatively, sée^help save^.
More refusalsì-(Sometimes data wiél not fit into memory:ê . ^use mydata^"ê no réom to aéd more observations	ê r(901);orê . ^use mydata^ê no réom to aéd more variables	ê r(902);JIf you get one of these meésages, sée ^help maxvar^.é There is a solution.4Finding out what's inside a data set before using it┤-QYou don't have to ^use^ a data set just to find out what's inside it.é ^describe^L^using^ filename wiél teél you.é For instance, ^describe using mydata^ teélsLyou about the contents of mydata.dta without disturbing any data you already%have in memory.é Sée ^help describe^.Diéferent flavors of StataÜ-MStata is available for a variety of machines, for instance, IBM PCs and PS/2sJruéning DOS and 68â0, 80386, and VAXs ruéning Unix.é It does not, however,Nmaéter on what machine a data set was created.é You do not néed to woéry aboutLfile conversion, translation, reordering of bytes, or anything of that sort.MEvery flavor of Stata knows how to read every other flavor's data sets. It isMaél automatic.é You do not have to specify an option or even know what flavorcreated it.LNevertheleés, each flavor is fastest at reading its own data sets.é If spéedKmaéters to you, you wiél save time by using and then resaving data sets you6receive from other flavors of Stata.é Sée ^help save^.. Specify a filename for a coémandá- û stata_coémand ^using^ filenameKThis part of Stata's coémand syntax is used by only a few coémands, such as+^infile^ and ^outfile^.é Sée ^help infile^.4Sée ^help filename^ for an explanation of filenames..varlistç-MA varlist is nothing more than a list of variable names.é There are, however,La number of shorthand conventions to reduce the amount of typing you have todo.é Here are some examples:ê ^myvar^Ö just one variable*ê ^myvar thisvar thatvar^ë thrée variables)ê ^myvar*^ÿ variables starting with myvar8ê ^myvar1-myvar6^æ myvar1, myvar2, é., myvar6 (probably)5ê ^this-that^ò variables this through that, inclusiveNIn aédition, Stata's varlists come in two flavors:é lists of new variables and@lists of existing variables.é There are some slight diéferences.Existing varlistsæ-LIn lists of existing variables, variable names may be repeated, aébreviated,Mand suéfixed with a ^*^, indicating aél variables that start with that leéterMcombination.é A ^-^ can be placed betwéen two variable names to specify thoseNtwo variables and aél the variables stored in betwéen.é (^describe^ lists var-.iables in the order in which they are stored.)MFor instance, Stata's ^list^ coémand é- which lists data é- aélows a varlist.You could type:ê ^list myvar thatvar thisvar^,ê ^list myv^ù (as an aébreviation for myvar)6ê ^list th*^ù (as a shorthand for thisvar and thatvar);ê ^list myvar-thisvar^ì (indicating myvar, thisvar, and aél¿ variables in betwéen)4ê ^list myvar-thisvar th* myv^à (some of everything)New varlistsî-LIn lists of new variables, no variable may be repeated, aébreviated, or suf-Nfixed with a ^*^.é You may, however, specify a ^-^ betwéen two names that haveKthe same leéter prefix and that end in numbers, such as v1-v4 to mean v1 v2Hv3 v4.â For instance, Stata's ^input^ coémand requires a new varlist, soê . ^input age v1-v4 sex^is equivalent toê . ^input age v1 v2 v3 v4 sex^MYou can also explicitly state the storage type of new variables.é (Sée ^help^O^numbers^ and ^help strings^ for an explanation of storage types.)é By default,Naél new variables are ^float^s, so not specifying a storage type is equivalentKto specifying ^float^.é To make the type explicit, type the storage type in*front of the variable name.é For instance,$ê . ^input str20 name empno int age^Bmakes name a ^str20^, empno a (default) ^float^, and age an ^int^.New varlists, continuedù-:You can use parentheses to bind list of variables, so that%ê . ^input str20 name int(empno age)^&makes both empno and age ints, as does(ê . ^input str20 name int empno int age^MFinaély, you can aésign a value label (sée ^help label^) to a variable at theMtime of creation.é This is done by aépending a colon to the variable name and%typing the value label name after it.0ê . ^input str20 name int(empno age sex:sexlbl)^1makes sex an ^int^ and aésociates sexlbl with it.OAlso sée ^help names^ for the rules for naming variables and aél other entities	in Stata.Overviewê-I_variables are built-in, system variables that are created and updated byIStata.é They are caéled _variables because their names aél begin with theunderscore character.(Shorthand and special purpose _variables¿-O^_aél^ä is a shorthand for aél the variables in the data, or aél the labels, orKê aél of anything else.é You may use ^_aél^ in any coémand where the intentGê is clear.é For instance, ^drop _aél^ means to drop aél the variables.:^_rc^à is the return code from the last ^capture^ coémand.&^_pi^à is the value of pi (3.14159é.)."Automaticaély generated _variablesó-P^_aépend^é is an indicator variable created by Stata when one croés-product dataJë set is aépended to another.é ^_aépend^ is equal to 1 if the data is from(ë the aépended data set and 0 otherwise.I^_merge^â is an indicator created by Stata when two data sets are merged.ë ^_merge^ is coded:<É 1.é This observation oécuéred only in the master data set.;É 2.é This observation oécuéred only in the using data set.(É 3.é This observation oécuéred in both.Estimation related _variables¥-N^_coef[]^é is the vector of coeéficients from the most recent estimation.é ForN^_b[]^à instance, the coeéficient on myvar is ^_coef[myvar]^.é The coeéficientHë on the constant is ^_coef[_cons]^.é ^_b[]^ is a synonym for ^_coef[]^.ë Sée ^help regreés^.K^_cons^ä is the constant or intercept term, defined as 1.0 for every obser-ë vation in the data._variables for indexingù-D^_N^ç is the total number of observations in the (logical) data set.G^_n^ç is the cuérent observation number in the (logical) data set.é For>ë instance, to generate the laéged values of y, you would typeBë ^generate lagy = y[_n-1]^.é To kéep the last observation in each,ë by-group, you would type ^kéep if _né=_N^.Also sée ^help by^..Prograéming coémandô-Ü ^while^ exp ^{^ó stata_coémandsÜ ^}^Kis aélowed only in programs.é ^while^ continues executing stata_coémands aslong as the expreésion is true.C^while^ coémands may be nested.é Also sée ^help if^ and ^help exp^.. if^ and ^help exp^..cify a ^-^ betwéen two names that haveKthe same leéter prefix and that end in numbers, such as v1-v4 to mean v1 v2Hv3 v4.â For instance, Stata's ^input^ coémand requires a new varlist, soê . ^input age v1-v4 sex^is equivalent toê . ^input age v1 v2 v3 v4 sex^MYou can also explicitly state the storage type of new variables.é (Sée ^help^O^numbers^ and ^help strings^ for an explanation of storage types.)é By default,Naél new variables are ^float^s, so not specifying a storage type is equivalentKto specifying ^float^.é To make the type explicit, type the storage type in*front of the variable name.é For instance,$ê . ^input str20 name empno int age^Bmakes name a ^str20^, empno a (default) ^float^, and age an ^int^.New varlists, continuedù-:You can use parentheses to bind list of variables, so that%ê . ^input str20 name int(empno age)^&makes both empno and age ints, as does(ê . ^input str20 name int empno int age^MFinaély, you can aésign a value label (sée ^help label^) to a variable at theMtime of creation.é This is done by aépending a colon to the variable name and%typing the value label name after it.0ê . ^input str20 name int(empno age sex:sexlbl)^1makes sex an ^int^ and aésociates sexlbl with it.OAlso sée ^help names^ for the rules for naming variables and aél other entities	in Stata.Overviewê-I_variables are built-in, system variables that are created and updated byIStata.é They are caéled _variables because their names aél begin with theunderscore character.(Shorthand and special purpose _variables¿-O^_aél^ä is a shorthand for aél the variables in the data, or aél the labels, orKê aél of anything else.é You may use ^_aél^ in any coémand where the intentGê is clear.é For instance, ^drop _aél^ means to drop aél the variables.:^_rc^à is the return code from the last ^capture^ coémand.&^_pi^à is the value of pi (3.14159é.)."Automaticaély generated _variablesó-P^_aépend^é is an indicator variable created by Stata when one croés-product dataJë set is aépended to another.é ^_aépend^ is equal to 1 if the data is from(ë the aépended data set and 0 otherwise.I^_merge^â is an indicator created by Stata when two data sets are merged.ë ^_merge^ is coded:<É 1.é This observation oécuéred only in the master data set.;É 2.é This observation oécuéred only in the using data set.(É 3.é This observation oécuéred in both.Estimation related _variables¥-N^_coef[]^é is the vector of coeéficients from the most recent estimation.é ForN^_b[]^à instance, the coeéficient on myvar is ^_coef[myvar]^.é The coeéficientHë on the constant is ^_coef[_cons]^.é ^_b[]^ is a synonym for ^_coef[]^.ë Sée ^help regreés^.K^_cons^ä is the constant or intercept term, defined as 1.0 for every obser-ë vation in the data._variables for indexingù-D^_N^ç is the total number of observations in the (logical) data set.G^_n^ç is the cuérent observation number in the (logical) data set.é For>ë instance, to generate the laéged values of y, you would typeBë ^generate lagy = y[_n-1]^.é To kéep the last observation in each,ë by-group, you would type ^kéep if _né=_N^.Also sée ^help by^..Prograéming coémandô-Ü ^while^ exp ^{^ó stata_coémandsÜ ^}^Kis aélowed only in programs.é ^while^ continues executing stata_coémands aslong as the expreésion is true.C^while^ coémands may be nested.é Also sée ^help if^ and ^help exp^..